I’m fairly new to jQuery and want to move past using explicit selectors and muddying up my code this way. I have tried a few different things but am unsuccessful at getting my selectors to dynamically function on multiple elements without having a snippet of code for each element.
My script is simply as follows:
<script type="text/javascript">
$(document).ready(function() {
$("#navItem").mouseenter(function(){
$(this).animate({
height: "150px"
}, 500, "easeOutBounce")
})
$("#navItem").mouseleave(function(){
$(this).animate({
height: "120px"
}, 500, "easeOutBounce")
})
</script>
And my HTML..
<div class="navWrap">
<div id="navItem" class="navButton blue"></div>
<div id="navItem2" class="navButton orange"></div>
<div id="navItem3" class="navButton green"></div>
<div id="navItem4" class="navButton red"></div>
</div>
I left out the remainder of the script because it’s repetitive (the same functions for the rest of the IDs you see in the HTML). My goal is to be able to dynamically select the “current” element that is being hovered over, rather than explicitly referencing each ID. I assume I need to use the “this” selector, but the documentation I’ve found I have trouble relating back to my scenario.
Any help is appreciated, thanks all!
selectors in jquery are basically the same as css selectors, so selecting by class will make a jquery object containing all elements with that class. http://api.jquery.com/category/selectors/
When you apply a jquery function typically
$(this)refers to a single specific element in question rather than the entire list, so use $(this) to effect elements selected by class will work fine. I you need multiple bindings to a group you should check out.eachhttp://api.jquery.com/each/I am using .hover here which is a shorthand for mouseenter and mouseleave http://api.jquery.com/hover/