Reputation: 8827
I have this inline javascript, is there any way it could be made unobtrusive? thanks.
<a href="/uploads/status/image/52/Zombatar_1.jpg" onclick="displayLightBox(this); return false;">
<img alt="Thumb_zombatar_1" src="/uploads/status/image/52/thumb_Zombatar_1.jpg">
</a>
Upvotes: 2
Views: 98
Reputation: 165941
As you've tagged the question with jQuery, I'll give you a jQuery answer. Your a
element currently has no identifying characteristic other than its href
attribute. It would be easiest to give it an id
and then use an id
selector. The key is simply find some characteristic by which you can identify the element you want to target.
If an id
or a class
is not an option, use an attribute selector:
$("a[href='/uploads/status/image/52/Zombatar_1.jpg']").click(function() {
displayLightBox(this);
return false;
});
Notice that I've removed the random false;;
from your inline event handler as as far as I can tell it serves no purpose whatsoever.
Update (see comments)
As you have multiple elements to bind the event handler to, your best bet will probably be a common class. You can then use a class selector:
$(".myLink").click(function() {
displayLightBox(this);
return false;
});
The click
event handler is bound to all elements in the matched set. When it executes, this
refers to the clicked element.
Upvotes: 3
Reputation: 17651
Definitely a good idea to keep your HTML markup and JavaScript code separate. I would recommend applying the onClick behavior to the link after it has been rendered. In my example, I use jQuery to bind the event handler function to the link:
$('#element_id').click(function() {
displayLightBox(this);
return false;
});
If you're writing large web applications, separating your business logic and presentation is essential for writing maintainable and supportable code.
Your jQuery selector will vary depending on how it's placed on the page. If you could provide the HTML context in which that link is created, I can provide a better suited jQuery selector.
Upvotes: 3