Reputation: 295
The goal is to have several elements trigger a specific text message for each one when the mouse if over it, and no text if neither one if hovered over. From other questions I found that $("#id").is(":hover")
should return true if the mouse is over the element, but it doesn't seem to do it. They all return false and the text is "None"
HTML:
<input class="r_check" type="checkbox" id="r1" name="rating" value="1"><label for="r1"></label>
<input class="r_check" type="checkbox" id="r2" name="rating" value="2"><label for="r2"></label>
<input class="r_check" type="checkbox" id="r3" name="rating" value="3"><label for="r3"></label>
<p class="text" id="the_text"></p>
Javascript/Jquery:
$(document).ready(function(){
var text = $("#the_text");
if($("#r1").is(":hover")){
text.html("Low");
}else if($("#r2").is(":hover")){
text.html("Medium");
}else if($("#r3").is(":hover")){
text.html("High");
}else{
text.html("None");
}
});
I tried to replace the input fields with simple <p id="r1">input 1</p>
elements to see if the label or the class of the inputs is preventing the hover event, but that didn't work either.
Upvotes: 1
Views: 7044
Reputation: 263
Your problem can be written in a much neater and easier way as below
<input class="r_check" type="checkbox" id="r1" name="rating" value="1" data-text="Low">
<input class="r_check" type="checkbox" id="r2" name="rating" value="2" data-text="Medium">
<input class="r_check" type="checkbox" id="r3" name="rating" value="3" data-text="High">
<p class="text" id="the_text"></p>
$(document).ready(function() {
$(".r_check").each(function() {
$(this)
.mouseover(function() {
$("#the_text").html($(this).attr('data-text'))
})
.mouseleave(function() {
$("#the_text").html('');
});
})
});
Upvotes: 3
Reputation: 560
What you're doing is testing if themouse is over it just once when the page is loaded, what you should do is using an event that's triggered when the mouse is over your input( either with jquery's $('selector').hover(handlerIn,handlerOut)
or with $('selector').on("mouseenter,function() {} )
;
Upvotes: 1
Reputation: 682
$("#id").on("mouseenter", function(e) { });
That should do it
Upvotes: 2