I’m using jQuery to rewrite the DOM to transform a no-JS HTML page into a JS-drive page. I’ve hit a glitch on transforming the image links. In the original code I have:
<div class="f">
<a href="images/Fig-03-2.png" target="_blank">
<img src="images/fig-03-2.png" alt="Fig 3.3" />
</a>
</div>
…and I want to transform it into:
<div class="f">
<a>
<img src="images/fig-03-2.png" alt="Fig 3.3" onclick="imagepop("fig-03-2.png")/>
</a>
</div>
I can’t figure out how to write the onclick attribute so that it contains the img src value as imagepop‘s argument. I tried:
$(".f a").attr('onclick', 'imagepop(' + $(this).attr('src') + ')' );
…but $(this).attr('src') returned “undefined”.
How should I fix my line of code or would it be better to read the img src attribute from inside the imagepop function?
**Note, I have not developed the page so that each div has a unique ID, and do not plan to do so. None of the elements inside the <div> tag have IDs assigned to them.
For what it’s worth, I wouldn’t. Instead, I’d use a function like this:
What that line, probably wrapped in a
readyhandler, does is: If the user clicks the image, it does theimagepopthing and cancels the event, which (amongst other things) prevents the link from firing.It’s called progressive enhancement. JavaScript-enabled user agents will use the above, and ones without JavaScript enabled will still see and follow the link. Remember that user-agents are not just browsers, they include crawlers, spiders, etc., and yes, browsers with JavaScript disabled.
Update: If you really want to handle it at the link level (which might be more keyboard-friendly), rather than image level, then:
…since it’s the
img, nota, element that has thesrc. (And no need to useattrhere, thesrcreflected property is supported by all major — and probably all minor — browsers.)