0

I need help on understand how the $(this) work exactly because i can't bring this simple code to work:

HTML:

<img style="cursor:pointer;" onclick="openfullsize();" src="/customimage/test.png"/> 

JS:

function openfullsize(){ var path = $(this).attr("src"); alert(path); } 

I wonder if there is anything i'm doing wrong or if I just don't understand how $(this) behave. $(this) should refer to the element from which it is invoked, right? in this case, it would be my img.

This should alert the content of the src attribute but it is undefined.

I would like this to be in Jquery please.

Thanks for your help and here is the JsFiddle

4
  • You're using old-fashioned event binding with your jQuery. It would work as you expect if you bound the event handler in JavaScript (via jQuery) instead of with an "onclick" attribute. Commented May 26, 2015 at 22:57
  • 1
    There is a lot going wrong here :P The event handler is in window.load in your jsfiddle, so that means it will not be seen on click. Inside of that handler, since it wasn't assigned using javascript this is window, so there is that. jQuery in your fiddle was never included either. Basically, you need to just add jquery, avoid inlining your event handler, and once you have converted to unobtrusive with a jquery or native handler, this will properly apply to the element and vuala, src will be available. Commented May 26, 2015 at 22:59
  • @MaxZoom Why ask for jsFiddles if we have snipplets ;) blog.stackoverflow.com/2014/09/… Commented May 26, 2015 at 23:11
  • @k0pernikus there was some code to display results in the snippet window. Do you know where to get it from? Commented May 26, 2015 at 23:14

1 Answer 1

1

You should bind the event-handler directly in the JS code instead of in the HTML like you're doing at the moment.

$("img").on("click", function(){ //$(this) will now work as expected }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Working nice and very well. Really like this. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.