Now, bear in mind I’m just trying to ensure that the code works by consuming the ready event here. I just want to make sure that the data I expect is getting pulled by jQuery. I’ve also tried the load event.
In the end I’d want to use the load or ready event to set the image initially and then of course use the hover event to change that image on hover.
I’ve tried a lot of the answers here on SO and just can’t seem to get this working, so hopefully y’all can help me.
JavaScript:
$(document).ready(function () {
$("#submenumain-link").ready(function () {
alert($(this).data()["selectedimage"]);
alert($(this).data()["hoverimage"]);
});
$("#submenumain-link").hover(function () {
alert($(this).data("selectedimage"));
alert($(this).data("hoverimage"));
});
});
HTML:
<li id="submenumain-link"
data-selectedimage="some-image.png"
data-hoverimage="some-other-image.png">
But for whatever reason the alert messages just state undefined. Am I missing something here?
EDIT
Note that if I place those same alert statements in the hover, it works as expected. What event could I use to do the initialization?
The real problem is that
readyshould not be used in this way. Thereadyevent should only be used with making sure the DOM is ready – http://api.jquery.com/ready/So technically, inside of
document.ready, all of the DOM is ready and should be available for these kinds of things. Inside ofdocument.ready, the value ofthisrefers to thedocumentelement, so you need to actually grab thelielement. Your code should be something like this:http://jsfiddle.net/XN2LV/