I've made a simple example with my problem so I guess it's easier for you to understand.
I have a few div
s which all have a grey color, but when you hover over one of them, you see they get their true color.
If I click one of them (and it alerts clicked) it should change the color and the .hover()
shouldn't work anymore on this element, until another one is clicked.
I'm sitting here one hour and don't get it to work:
.test { background-color: #ccc;}
<div class="test" id="d1"></div>
<div class="test" id="d2"></div>
<div class="test" id="d3"></div>
and the script:
$(function() {
$('#d1').hover(function() { $(this).css('background-color', '#F00'); }, function() { $(this).css('background-color', '#CCC'); });
$('#d2').hover(function() { $(this).css('background-color', '#F0F'); }, function() { $(this).css('background-color', '#CCC'); });
$('#d3').hover(function() { $(this).css('background-color', '#00F'); }, function() { $(this).css('background-color', '#CCC'); });
$('#d1').click(function() { $(this).css('background-color','#F00'); alert("clicked")});
$('#d2').click(function() { $(this).css('background-color','#F0F'); alert("clicked")});
$('#d3').click(function() { $(this).css('background-color','#00F'); alert("clicked")});
})
for the link click here
It seems that the hover still works and it removes the background color immediately.
Thanks in advance!
Here you go with a really simple solution:
LIVE DEMO
having this HTML:
and both classes in CSS:
Well, without too many changes to your code [refactoring]:
Changes:
As an aside, I would probably use CSS classes and set
.active
to the clicked elements, and use.test:hover
. But I assume this was a rudimentary JavaScript example for learning purposes.And if you wanted to see the one with CSS: http://jsfiddle.net/MgTr4/1/
HTML
CSS
JS
Sample http://jsfiddle.net/sheeban/gEftm/3/
You can simplify the code greatly by using classes, and the jQuery methods
.addClass
and.removeClass
Working jsFiddle here
HTML:
jQuery/javascript:
CSS:
To simplify it even more, you can remove the
class="test"
from all DIVs, and change the hover selector to:This will not interfere with detecting the
click
event on the same collection of selectors.It's better to use css in this situation. JavaScript solution is more complicated. In your case you can change your "hover" block of code and change it to css rules:
Here is an example: jsFiddle, after edit: jsFiddle2