I have ten elements on a page with the same class.
When I hover over one of them I want to alter the other nine.
Here's what I have so far...
$("*[class='myClass']:not(this)").css({"top":"10px"});
Any ideas?
Using the attribute selector to select by class is a little redundant (not to mention slow) as there is a class selector. Try this:
$(".myClass").mouseover(function() {
$('.myClass').not(this).css({"top":"10px"});
});
If you want to reset the effect on mouseout, use hover()
with two function parameters. Also, it's better in this case to use a class.
$(".myClass").hover(function() {
$('.myClass').not(this).addClass('foo');
},
function() {
$('.myClass').not(this).removeClass('foo');
});
.foo { top: 10px; }
Use .not
method :
Remove elements from the set of matched elements
$("*[class='myClass']").not(this).css({"top":"10px"});
You can use either this:
$(".myClass:not(:hover)")
or this:
$(".myClass").not(":hover")
or this:
$(".myClass").not(this)
The last one assumes you're inside a mouseover
or mousenter
(or hover
) event handler. I also believe you have to reset the style on mouseout. Working demonstation: http://jsfiddle.net/tt8cz/
You can use the .not
method, which accepts a jQuery object, too:
$('.myClass').not($(this)).css({"top":"10px"});
The docs don't mention this possibility at first glance, but one of the first comments do
You could also do this with just CSS:
HTML:
<ol id="items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ol>
CSS:
#items:hover > li { padding-left:5px; }
#items:hover > li:hover { padding-left:0; }
I've used padding-left
, but you can use any property ofcourse.
JSFiddle .
If I correctly understand what you're trying to do, you can just change the style on all elements of .myClass
, then change it back on this
:
$('.myClass').hover(function() {
$(".myClass").css({"background":"blue"});
$(this).css({"background":"red"});
});
Or also handle the hover out state as Rory McCrossan suggested.
I made the next sample using background-color parameter.
$(document).ready(function(e) {
$('.myClass').live('mouseover',function(){
var element = $(this);
$(this).css({"background-color":"#FF0000"});
$('.myClass').each(function(){
if(element.html() != $(this).html()){
$(this).css({"background-color":"#FFFFFF"});
}
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.