Reputation: 33996
I have a button like below. I have a list of buttons. When user clicks it, I run a javascript function and it makes an ajax request, if request response is success, then I change status attribute of button tag. I change it from 1 to 2.
When the attribute status=1, I want user to see some text when hovering on button.
When the attribute status=2, I don't want him to see anything on button hover.
I tried like below but after status=2, still button text changes on hover. How can i fix this?
<button onclick="dosomething()" id="someid" status="1">name</button>
<script>
function dosomething(){
$.ajax({
type:"GET",
url:"somefile.php",
success : function(data) {
if (data == '200') {
$('#someid').attr('status', '2');
}
},
error : function() {
alert('error');
},
})
}
$(document).ready(function() {
updateHoverStates()
});
$(document).change(function () {
updateHoverStates()
});
function updateHoverStates() {
$('button[status=1]').hover(
function () {
$(this).text('You are hovering');
},
function () {
$(this).text('You are not hovering');
}
);
}
</script>
Upvotes: 0
Views: 2900
Reputation: 2223
jsFiddle: http://jsfiddle.net/ajzsv/20/
<button onclick="dosomething()" id="someid" status="1">name</button>
<script>
function dosomething()
{
$('#someid').attr('status', '2');
$('#someid').unbind('hover');
}
$(document).ready( function()
{
$('button').each( function()
{
$(this).hover(
function ()
{
$(this).text('You are hovering');
},
function ()
{
$(this).text('You are not hovering');
});
});
});
</script>
Upvotes: 1
Reputation: 787
This may work, that way the event is checking the staus attr each time it is called, instead of just once at bind time.
function updateHoverStates() {
$('button[status]').hover(
function () {
if($(this).attr('status') == '1')
$(this).text('You are hovering');
},
function () {
if($(this).attr('status') == '1')
$(this).text('You are not hovering');
}
);
}
As a side note, I believe data-status
would be a better supported way of having custom attributes, this also would allow the use of .data('status')
instead of .attr('status')
.
Alternatively you may be able to use CSS to simulate that
button[status="1"]:hover {
//possible attributes here
}
Upvotes: 3
Reputation: 8609
You once set the hover function for all buttons that matched the selector button[status=1]
. You changed the status
attribute later, but that doesn't detach the hover event listeners from those buttons.
In the function where you set
$('#someid').attr('status', '2');
you should simply remove the event listener manually.
$('#someid').unbind('hover');
Upvotes: 0
Reputation: 36602
change
events don't bubble up to the document, so updateHoverStates
is probably not being called a second time.
Upvotes: 0