Changing a specific Instance without ID - javascript

Ok, let's say that I have multiple links on a page and I want links to change background color when you roll over them. I would use this code:
$(function() {
$('a').mouseover(function() {
$('a').css('background-color', 'black');
});
});
$(function() {
$('a').mouseleave(function() {
$('a').css('background-color', 'white');
});
});
the problem with this code is that when you roll over one a, all of the links change color. I could give each a a specific ID and make a specific function for each, but is there a more efficient way to do this?
Edit: Additionally, what could I do to set the original background color back to the way it was. If I turn the background back to white, It might not have been white in the first place. How could I fix this?

In your version you use $('a') to call the .css() function on. The Problem is that $('a') selects ALL the a nodes on the page and not only the one that you moved your mouse over. Within the mouseover callback function the this keyword references the node that was the originator of the event. So when you do $(this) within that function you'll create a jQuery object (called a wrapped set) of that node. Now you can call all jquery functions on it, uncluding the .css() function. So here you go:
$(function() {
$('a').mouseover(function() {
$(this).css('background-color', 'black');
});
});
$(function() {
$('a').mouseleave(function() {
$(this).css('background-color', 'white');
});
});

Just so you know, you're all going about it the long and hard way.
// this is like document.onload = function,
// this only needs to be called once, you can put
// all your jQuery in this one function
$(function() {
// the following is a call to all `a` links to add jQuery's own .hover function
// see -> http://api.jquery.com/hover/
$("a").hover(function(eIn) { // this first function is the action taken when
// user hovers over the link
$(this).css({ 'background-color': '#000', 'color': '#fff' });
}, function(eOut) { // this second function is what happens
// when user hover away from the link
$(this).css({ 'background-color': '', 'color': '' });
});
});
​See WORKING Fiddle
ALSO, YOU DONT NEED JQUERY FOR THIS, USE CSS
In CSS:
a:hover {
background-color: #000;
color: #fff;
}​
See it in CSS ONLY HERE

Related

ToggleClass not on all divs

I'm working on a pricing table with some hover.
You can see it right here: http://lhit.nl/lucid/
As you see, when you hover on a pricing table all the divs toggle the classes.
And thats not what I want. I want it to be seprate ofcourse.
My jQuery:
$('.package').hover(function(){
$('.name').toggleClass('name-hover')
$('.price-container').toggleClass('price-hover')
$('.price').toggleClass('white-hover')
$('.month').toggleClass('white-hover')
});
The css is just to overwrite current colors:
.package .price-hover {
background: #008ed6;
}
.package .white-hover {
color: #fff;
}
I already tried to use $(this) but it doesn't work.
$('.package').hover(function(){
$(this).find('.name').toggleClass('name-hover')
$(this).find('.price-container').toggleClass('price-hover')
$(this).find('.price').toggleClass('white-hover')
$(this).find('.month').toggleClass('white-hover')
});
This can be simply achieved just by css. Why to add Js for this ?
package:hover .price-container{
background: #008ed6;
}
You could use each():
$('package').each(function() {
var _this = this;
$(this).hover(function() {
$(_this).find('.name').toggleClass('name-hover')
$(_this).find('.price-container').toggleClass('price-hover')
$(_this).find('.price').toggleClass('white-hover')
$(_this).find('.month').toggleClass('white-hover')
});
})
First you need to use find to only change the classes for elements
inside the currently hovered over .package, otherwise it will
change classes for all these elements.
Secondly, hover event takes
2 functions, one when mouse enters the hover area, second when cursor
exits the hover area. The way you are handling hover event, it toggles the classes twice, once on hover in, once on hover out, so in the end leaving it same as before.
Try this code:
$('.package').hover(function(){
$(this).find('.name').addClass('name-hover');
$(this).find('.price-container').addClass('price-hover');
$(this).find('.price').addClass('white-hover');
$(this).find('.month').addClass('white-hover');
}, function(){
$(this).find('.name').removeClass('name-hover');
$(this).find('.price-container').removeClass('price-hover');
$(this).find('.price').removeClass('white-hover');
$(this).find('.month').removeClass('white-hover');
});
$(".package").hover(function() {
$this = $(this);
$this.find(".name").toggleClass("name-hover");
$this.find(".price-container").toggleClass("price-hover");
$this.find(".price,.month").toggleClass("white-hover");
});
#Spartak Lalaj As of jQuery 1.4 the .hover() may have one parameter. See https://api.jquery.com/hover/

Change CSS for one ID using this.id

I have to div like this:
<div class="vignettes" id="vignette1"></div>
<div class="vignettes" id="vignette2"></div>
I want to do the same thing on Hover event for both div, let's say change the background to black:
$('.vignettes').hover(function ()
{
//$('.vignettes').css("background", "#000");
$(this.id).css("background", "#000");
},
function()
{
});
The commented line works, but obviously change both div to black when I hover one of them. I want to change only the hovered one. Instead of cloning my hover function with good ids, I want to get the id of the hovered one and change its background dynamically.
The code alert(this.id) pops up the good id, so this.id works.
But $(this.id).css("background", "#000#"); doesn't do anything.
JSFiddle sample
As this is the target, just use $(this).css("background", "#000");
e.g.
$('.vignettes').hover(function ()
{
$(this).css("background", "#000");
},
function()
{
});
It is a bit silly to use a selector to find the current element by its own id as suggested
In fact, most of the time, you do not even need IDs to do this sort of operation, just use classes to change the styling:
e.g. http://jsfiddle.net/TrueBlueAussie/cLws40vr/8/
$('.vignettes').hover(function () {
$(this).addClass("selected");
console.log("test");
},
function () {
$(this).removeClass("selected");
});
You just need to use $(this)
When you are in a function like this, using $(this) will apply to the current element the event applies to.
$('.vignettes').hover(function ()
{
$(this).css("background", "#000");
},
function()
{
});
Updated JSFiddle - http://jsfiddle.net/cLws40vr/4/
As most of the other answers have suggested using this as the selector is the correct way to accomplish what you are trying to do in this case.
$(this).css("background", "#000");
There is another error in your code that was causing your original code not to work. To select using an id you need to add the hash symbol to the beginning of the selector string.
$('#' + this.id).css("background", "#000");
I just thought I would point that out in case anyone was wondering why the original code didn't work.
$(this).css("background", "#000");
alert($(this).attr('id'));
Fiddle http://jsfiddle.net/cLws40vr/5/

Using onClick to change classes with javascript

I'm working on a menu which animates each li's padding and color properties on mouseover and mouseout, and I wanted to stop the animations and color changes by changing the link's class. So far, I've assigned the animations to stick with a.inactive, and wanted to change the class to a.active through an onclick event. So far, I've found some helpful resources on this site which I'll paste below.
$("#menu li a").click(function (){
if (!$(this).hasClass("inactive")) {
$("a.inactive").removeClass("inactive");
$(this).addClass("active");
}
});
The code above seems to be the ticket, but being a total noob to javascript, I'm having trouble creating a function out of it that can be executed via onClick. Here's the html:
<ul id="menu">
<li class="landscape-architecture"><a class="inactive" href="#project1" onclick="changeClass();"><span class="menu_year">2006/</span>AQUEOUS PLAN</a></li>
Any help would be greatly appreciated. Thanks!
EDIT - Since the code you all have provided below should work but does not, I've gone ahead and put in the code for the mouseover/mouseout animations to see if for some strange reason there would be a conflict:
$('#menu li').click(function () {
window.location = $(this).find('a').attr('href')
}).mouseover(function (){
$(this).find('a.inactive')
.animate( { paddingLeft: padLeft, paddingRight: padRight}, { queue:false, duration:100 } )
.animate( { backgroundColor: colorOver }, { queue:false, duration:200 });
}).mouseout(function () {
$(this).find('a.inactive')
.animate( { paddingLeft: defpadLeft, paddingRight: defpadRight}, { queue:false, duration:100 } )
.animate( { backgroundColor: colorOut }, { queue:false, duration:200 });
});
The above code works for you? Assuming you have a jQuery library loaded in your file, after changing your second line to:
if ($(this).hasClass("inactive")) {
It seems to work fine! The function you have there will run whenever the specified <a> element is clicked. You don't even need the onclick element in the HTML.
If however you do want to utilize the onclick element and turn your current code into a function that may be able to be used elsewhere, you could do something like:
function change_class() {
if ($(this).hasClass("inactive")) {
$(this).removeClass("inactive").addClass("active");
}
});
And use onclick="change_class()" in your HTML.
Here's a JSFiddle to test with: http://jsfiddle.net/TVms6/
Check out this http://api.jquery.com/toggleClass/
$("#menu li a").click(function (){
$(this).toggleClass('inactive')
});
This is not the recommended way of doing stuff these days. While onclick() will work for you, it doesn't quite fit into the unobtrusive policy that people tend to follow with JavaScript these days. Read the description at Wikipedia.
What you should be doing is something like
$('selector').click(function(){
//the action that you want to perform
});
You can assign an id to your anchor tag to be able to easily target it.
In my opinion its best to learn the correct way while you start learning itself, that way it becomes more of a habit from early on.

Reverting jquery animations back to original css states

I've got a page of elements, each of which, depending on user interaction, may be animated away by the given function:
function slideAndFade(id){
$(id).animate({opacity: 'toggle', width: 'toggle'}, 500);
}
I want to create a reset function that brings all the elements back onto the page. Running all the elements through the toggle function above won't work, because currently hidden elements will be shown, and currently shown elements will be hidden.
Essentially looking for way to revert all elements to their original css states, regardless of whether they've been acted upon by jquery animation.
Thanks-
Edit:
Just realized all I need to do is replace 'toggle' with 'show':
function revertSlideAndFade(id){
$(id).animate({opacity: 'show', width: 'show'}, 500);
}
Calling this on any element will ensure the element is reverted back to visible in this case. However, see Nick's answer below for a more generally applicable approach.
If you could identify all the elements that might be passed into this function, say they had a class .toggleElem you could use that to store the values on page load and restore then when needed, like this:
$(function() {
$(".toggleElem").each(function() {
var $this = $(this);
$.data(this, 'css', { opacity: $this.css('opacity'),
width: $this.css('width') });
});
});
Then you could restore them at any point later:
function restore() {
$(".toggleElem").each(function() {
var orig = $.data(this, 'css');
$(this).animate({opacity: orig.opacity, width: orig.width}, 500);
});
}

Click link when clicking LI

Ok, I have this list layout that I use, and I want the list row to highlight when I hover it. Now, that's not a problem really, since I can use javascript to change classes for example, but I want the cursor to change to a pointer when hovering and when clicked, I want to follow the link within.
Example code can be found here:
http://sandman.net/test/hover_links.html
I also want to highlight the LI only when there is an eligible link inside it. Preferably using jQuery... Any ideas?
--
I've edited the code to incorporate the suggestion below, and the problem is that the click() action fires when I click other items inside the LI...
--
Right, so now I've edited the code. I've added a class to the link(s) that SHOULD be followed on click, and then a event.stopPropagation() on the links that does NOT have this class, so they are handeled by the browser accordingly.
Thanks again!
jQuery('li:has(a)')
.css('cursor', 'pointer')
.hover(function(){
jQuery(this).addClass('highlight');
}, function(){
jQuery(this).removeClass('highlight');
})
.click(function(e){
if (e.target === this) {
window.location = jQuery('a', this).attr('href');
}
});
This worked for me
$('#element li').hover(function() {
$(this).animate({
backgroundColor: "#4CC9F2"
}, "normal")
}, function() {
$(this).animate({
backgroundColor: "#34BFEC"
}, "normal")
});
I used jquery.color.js plugin it animates really nice hover effect color change

Categories