Can somebody please explain to me why this doesn’t work?
I’m sorry I’m a total starter on javascript + jQuery.
Here’s the code:
Javascript / jQuery:
<script type="text/javascript">
$('.clickk').click(function(e){
window.location.href = $(this).find('a').attr('href');
});
</script>
HTML:
<div class="clickk" >
<a href="google.com">link</a>
blah blah blah.
</div>
Please help me find what I’m missing.
Thanks in advance. Hoping the question is clear.
Two probable issues:
You’re probably executing that script before any elements with that class exist in the DOM (more below).
The
hrefshould start withhttp://, e.g.,href="http://www.google.com"orhref="http://google.com". Justhref="google.com"makes it a relative link, which won’t work reliably.Assuming you fix #2, here’s some detail on #1:
Won’t work:
There are two ways to fix this:
Put the script at the end of the page
This is usually the preferred way, put your scripts at the end of the page, not the beginning.
Works:
This also reduces apparent page load time by not holding up rendering while waiting for the scripts to download. See YUI’s guidelines (or any of several others). DOM elements defined above a script are accessible to that script. DOM elements defined below the script are not (unless you do something like the following to delay things).
Use the
readyeventIf for some reason putting the scripts at the end doesn’t suit, you can use the
readyevent:Works:
Note that passing a function into
jQuery(or into$, which is just an alias forjQueryunless you usenoConflict) is the same as passing one into$(document).ready(...); details: http://api.jquery.com/jQuery/#jQuery3