Reputation: 3393
$(".outerdiv .innerdiv").hover(function(){
var variable = $(this).index();
});
var variable = 3;
$("span").html(variable);
the original html of <span>
is set as 3 using jquery but when hovering over an .innerdiv
i want it to change to its index value by changing the variables outside the function to the index value of the specific .innerdiv
that was hovered on. http://jsfiddle.net/eEUeT/9/
<div class="outerdiv">
<div class="innerdiv">1</div>
<div class="innerdiv">2</div>
<div class="innerdiv">3</div>
<div class="innerdiv">4</div>
<div class="innerdiv">5</div>
</div>
<span></span>
I have tried http://jsfiddle.net/eEUeT/11/ this does not have a set orginal value of 3 however.
AND i understand by changing the html to <span>3</span>
and using the jquery below will work but i would rather learn how to do it the way i asked
$(".outerdiv .innerdiv").hover(function(){
var variable = $(this).index();
$("span").html(variable);
});
Upvotes: 2
Views: 1066
Reputation: 75993
If you want to manipulate an element, you have to select it... you can't assign a value to a variable and expect the DOM element to update itself. As you stated though, it's easily enough done like this:
//set the initial HTML for the span element(s)
var $span = $('span').html(3);
$(".outerdiv .innerdiv").hover(function(){
//update the span element(s) HTML to the index of the hovered-over `.innerdiv` element
$span.html($(this).index());
});
This places the index of the hovered-over .innerdiv
element as the HTML of any <span>
elements.
Here is a demo: http://jsfiddle.net/eEUeT/14/
Upvotes: 1