I'm not quite sure if I'm not using this in the correct scope or what, but I have a script that basically captures a link click and causes the page to fade out before going to the linked page. However, if the link is a JavaScript onclick, the script fails.
Here's my code:
<script type="text/javascript">
pageObj = {
init: function(){
$("body").fadeTo("slow", 1);
},
redirectPage: function(redirect){
window.location = redirect;
},
linkLoad: function(location){
$("body").fadeOut(1000, this.redirectPage(location));
}
};
$(document).ready(function() {
pageObj.init();
$("a").click(function(e){
e.preventDefault();
if (this.attr('onclick') !== undefined) {
eval(this.attr('onclick').val());
} else {
var location = this.href;
pageObj.linkLoad(location);
}
});
});
</script>
As you can see, I'm trying to do a check to see if the link has the onclick attribute, and then call the onclick function if it exists. How can I achieve this?
Use:
$(this).attr
instead ofthis.attr
This forces it into the context of jQuery.
While Diodeus is correct that you need to wrap
this
in a jQuery collection before usingattr()
(it's a method of a jQuery collection, not of anHTMLElement
), you can just as well skipattr()
.Note that I used the property (when an HTML document loads, attributes are usually preloaded into properties, with
on_______
attributes being preloaded as methods. Also note that I usedthis.onclick.call()
rather thaneval()
, setting the correctthis
foronclick
methods, and ensuring access to the event object as an argument.