jQuery :hover selector [duplicate] - javascript

I need to define a div's background color on :hover with jQuery, but the following doesn't seem to work:
$(".myclass:hover div").css("background-color","red");
How can I get the same result? It's important that it has to be done with jQuery but for some reason it doesn't work. Any suggestions? Thanks!

I would suggest to use CSS over jquery ( if possible) otherwise you can use something like this
$("div.myclass").hover(function() {
$(this).css("background-color","red")
});
You can change your selector as per your need.
As commented by #A.Wolff, If you want to use this hover effect to multiple classes, you can use it like this
$(".myclass, .myclass2").hover(function(e) {
$(this).css("background-color",e.type === "mouseenter"?"red":"transparent")
})
Js Fiddle Demo

You can try this:
$(".myclass").mouseover(function() {
$(this).find(" > div").css("background-color","red");
}).mouseout(function() {
$(this).find(" > div").css("background-color","transparent");
});
DEMO

I know this has an accepted answer but if anyone comes upon this, my solution may help.
I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.
For instance, the css:
.nohover:hover {
color: black !important;
}
Then with jQuery:
$("#elm").addClass("nohover");
With this method, you can override as many DOM elements as you would like without binding tons of onHover events.

Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.
If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.
Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:
$('head').append('<style>.myclass:hover div {background-color : red;}</style>')
If you want to read more on adding CSS with javascript you can check out
one of David Walsh's Blog posts.

Use JQuery Hover to add/remove class or style on Hover:
$( "mah div" ).hover(
function() {
$( this ).css("background-color","red");
}, function() {
$( this ).css("background-color",""); //to remove property set it to ''
}
);

It's too late, however the best example, how to add pseudo element in jQuery style
$(document).ready(function(){
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});
$("a.dummy").hover(function() {
$(this).css("background-color","#0670c9")
}).mouseout(function(){
$(this).css({"background-color":"#003d79",});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<a class="dummy" href="javascript:void()">Just Link</a>

Related

JavaScript: How can I change the class of a div by clicking another div?

I want to make a div appear when I click on another div. I was thinking of doing this by using JavaScript to change the class of the div when the other div is clicked on.
This is the HTML of the div I want to appear:
<div id="menutext1" class="hidden"></div>
This is the HTML of the control div (the one to click on to make the above div appear):
<div id="menu1"></div>
This is the CSS:
.hidden { display: none; }
.unhidden { display: block; }
I've looked everywhere and nothing seems to work for me!
I don't have much experience with JavaScript or JQuery but I can understand it.
Thanks in advance :))
.addClass(), .removeClass() should do what you need. .toggleClass() might also be useful. You want to do something like this in your onClick() method:
$('#menu1').click(function() {
$('#menutext1').addClass('unhidden')
});
Swap in toggleClass() if you want to be able to hide/unhide. I should add that these are JQuery functions so make sure to include JQuery in your project.
You have several options to achieve this:
$('#menu1').on('click', function(){
$('#menutext1').show();
// OR
$('#menutext1').toggleClass('hidden unhidden');
// OR
$('#menutext1').removeClass('hidden ').addClass('unhidden');
});
Demo
Note: When working with jQuery and DOM-Manipulation have a look at the .ready() function.
Reference
.on()
.toggleClass()
.removeClass()
.addClass()
.show()
You can do it without JQuery using the classList.toggle method. And you don't really need the unhidden class. When the hidden class is toggled off, the div should return to its default display (block).
// get the element you want to click on
var controlDiv = document.getElementById('menu1');
// assign a function to run when it is clicked
controlDiv.addEventListener('click', function() {
// turn the hidden class off or on
document.getElementById('menutext1').classList.toggle('hidden');
});

How to hide elements when another element is clicked

Having a bit of difficulty getting this jquery to work. I have a form where all fields are nested in a div.form-group. The subscribe button has an id of subscribe.
I want the form fields to disappear on click... but my js is not working out. Here's what I've tried, to no avail:
(function($) {
window.onload = function () {
$("#subscribe").click(function() {
$(".form-group").css("display: none");
});
}
})(jQuery);
The form-group class is set to display: block in the CSS.
Is there something obvious I'm missing here? Any help is greatly appreciated.
cheers,
jQuery provides a .hide() method as a shortcut to setting the various CSS directives that hide an element (display: none and visibility: hidden, for example).
$(".form-group").hide();
If you prefer to set the CSS directly, place quotes around both elements of the statement:
$(".form-group").css("display", "none");
$(".form-group").css("display: none");
supposed to be
$(".form-group").css("display", "none");
**OR**
$(".form-group").css({ "display" : "none"});
you have been trying to set the attribute as a single string.
It is supposed to be comma separated if it's only a single attribute that you want to change.
Or an object if you want to target multiple css properties at the same time.
$("#subscribe").click(function() {
$(".form-group").hide()
});
}
$( "#anotherid" ).on('click', function() {
$( "#idhere" ).hide('slow');
});
Try this

Using html text as selector for CSS with JS?

I'm sure others have asked this but I just cant' find anything that helps me.
Have a look at this code on jsfiddle.
Both Person1 and Person2 have
class="from"
And the CSS selector is .from so it applies to both but I'm trying to achieve that it only applies to Person1 with JavaScript/jQuery.
I've tried numerous things such as
$( "span.from:contains('Person1')" )
with no success. How should I do this?
Help would be much appreciated :)
In your case you can use filter()
$("span.from").filter(function(){ return this.innerHTML == "Person1"; })
to remove the animation of the item remove the from class using removeClass()
$("span.from").filter(function(){
return this.innerHTML == "Person1";
}).removeClass('from');
$( "span.from:contains('Person1')") works just fine. But in css you are still affecting all elements with .from class. After you get the element with Javascript, you should do something with it, like add a new class, and change the css so that the animation runs only on the new class.
$( "span.from:contains('Person1')").addClass('newClass')
CSS:
.newClass{
-webkit-animation: color-change 1s infinite;
...
}
Your code can work
$("span.from:contains('Person1')").text()
See this fiddle
If you are using straight up CSS you should be able to select just the first item using the nth-child selector:
.from:nth-of-type(1) { /* styles here */ }
If you wanted to select the first item via JS you would simply need to use eq() to grab the first item by index. This is chainable, so you could continue to set set CSS on this item similar to this (so in this example I'm adding an extra class on the first .from, and also setting its background color):
$(".from").eq(0).addClass("first-item").css("backgroundColor", "orange");
You can try with .not()
$(".from:not(span:contains('Person2')):eq(0)")

jQuery: Modify appended object's CSS

$('#foo').css({color:'black'}).append('<div>bar</div>').css({color:'red'});
Given the above, the css() method is applied to foo, but how could you get it to apply to the div that wraps "bar"?
The only way I could think of to do this in the same execution line would be to create a jQuery div object inside of the append(function(){ ... }) and apply the styling there.
Note: I'm trying to avoid inline styling (eg .append('<div style="color:red;">bar</div>')).
Update: I'm actually applying css to foo as well; The example has been updated to reflect this
You can flip the chain around so .css() runs on the appended element by using .appendTo() instead, like this:
$('<div>bar</div>').appendTo('#foo').css({color:'red'});
//or:
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
//or:
$('<div />', { text:'bar', css: {color:'red'} }).appendTo('#foo');
Try this:
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
$('#foo').append($('<div>bar</div>').css({color:'red'}));
or $something like
$('#foo').append($('<div />').text('bar').css({color:'red'}));
Easiest way is to use appendTo() rather than append():
$('<div>bar</div>').css({color:'red'}).appendTo('#foo');
You can find a working sample here: http://jsfiddle.net/YdzGZ/
what about:
$('#foo').append('<div>bar</div>').end().css({color:'red'});
How about you take a step back from the dynamic approach and create a rule or two in css?
#foo { color: black; }
#foo div,
#foo .orViaSomeClassName { color: red; }
No need to monkey about with injected inline styles that way.
And finally yet another approach to getting to the appended div:
$('#foo')
.css('color', 'black') // css on #foo
.append('<div>bar</div>') // appended to #foo
.find('div')
.css('color', 'red'); // css on divs inside #foo

alter divs css with javascript

Can I change style of some div link. Here is what I mean
<div id="somediv">something/div>
Lets say I have css like this :
#somediv a{
color:#000;
}
Now for instance upon some action such as mouse click on any element I want to change somediv a link css to
#somediv a{
color:#00ffff;
}
I know how to select div, by using Document.get.elementById('somediv') Is it possible to select a by using above method or any other?
Thank you
DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..
If you just want to apply a style to a particular element, it's very easy to do:
document.getElementById('whatever').style.color = '#f0f';
If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.
CSS:
#someDiv a {
color: #000;
}
#someDiv.awesome a {
color: #f0f;
}
Javascript:
document.getElementById('someDiv').className = "awesome";
Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.
If you're using jQuery or YUI, there's some good info in question 1079237
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';
assuming the A tag will be the first element inside your DIV
You could use CSS behaviors for this:
For instance:
#somediv a:hover
{
color:#0ff;
}
Otherwise, you may create a dedicated class (used when an element is click for example):
#onclickclass
{
color:#0ff;
}
Then in JavaScript, on onClick event, do:
document.getElementById('somediv').className = 'onclickclass';
And to change the style use
document.getElementById('somediv').className = 'your-css-class';
If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.
As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.

Categories

Resources