JSFIddle not working with Jquery
While working on an answer to this question I created this jsfiddle. For some reason it isn't working, and when I used firebug's error consol it was returning that ".show" is not a function. This leads me to believe that jsfiddle is incorrectly loading jQuery. Are there any known issues between JSFiddle and jQuery? Is my code simply incorrect (BTW when I change .show("slow")
to .style.display = "inherit"
it works fine whic开发者_JAVA技巧h is why I think it has to be a problem with jQuery...)
A working JSFiddle would be greatly appreciated.
A couple of issues:
- You forgot a
}
. - You're calling jQuery methods on elements that aren't wrapped in a jQuery object. You would need to do:
$(itemName.getElementsByTagName("span")[0]).show("slow");
(Note the wrapping). jQuery methods don't magically extend default elements, the object must be wrapped first.
Note now that this version works.
EDIT:
Alternatively, you could use the second parameter of jQuery's construct (scope) and shorten this code:
function showy(itemName) {
$('span:first',itemName).show("slow");
}
function closy(itemName) {
$('span:first',itemName).hide("slow");
}
EDITv2
Juan brought up a good point, you should also separate javascript with markup. By this I mean avoid using the on* attributes of the elements, and keep the bindings within the external .js file or <script>
tags. e.g.
<head>
...
<script src="http://path.to/jquery.js">
<script>
$(function(){ // execute once the document is ready (onload="below_code()")
// bind to the buttons' hover events
// find them by the "button" and "white" class names
$('.button.white').hover(function(){ // hover event (onmouseover="below_code()")
// find the first span within the link that triggered the event
$('span:first',this).show('slow');
},function(){ // mouse out event (onmouseout="below_code()")
// likewise, find first span
$('span:first',this).hide('slow');
});
});
</script>
...
</head>
<body>
...
<a href="#" class="button white" id="button1">
<span id="spanToShow">SHOW: this text </span>
on hover
</a>
...
</body>
I modified it to this:
function showy(itemName) {
$(itemName).find("span").show("slow");
}
function closy(itemName) {
$(itemName).find("span").hide("slow");
}
See: http://jsfiddle.net/ttweX/
I am really not a fan of obtrusive javascript :p
You should get used to never ever using the inline event handlers, and instead use jQuery's event binding.
Better solution:
http://jsfiddle.net/ttweX/2/
Also the one Tomh linked does some weird infinite blinking obnoxiousness.
$(function(){
$('a.button').hover(
function(){
$(this).find('span').show('slow');
},
function(){
$(this).find('span').hide('slow');
}
)
});
精彩评论