I'm busy on a register form. One of the steps is to choose your gender:
now, the desired result is, if someone clicks the male icon, the icon gets a blue color, and when someone clicks the female one, that one turns pink.
The color switching thing works when hovered, but not when clicked. This is my HTML:
<div id="submenugender">
<div class="submenu"><div class="sprite male" id="setmale"></div></div>
<div class="submenu"><div class="sprite female" id="setfemale"></div></div>
</div>
It seems pretty simple. So the .sprite
class is loaded, which just sets de default height and width + it loads the sprite. Then the male
and female
classes are loaded, which contain a background-position
element:
#registercontainer .submenu .male {
background-position: -7px -462px;
}
#registercontainer .submenu .female {
background-position: -60px -462px;
}
#registercontainer .submenu .male:hover, #registercontainer .submenu .male .active {
background-position: -7px -397px;
}
#registercontainer .submenu .female:hover, #registercontainer .submenu .female .active {
background-position: -60px -397px;
}
There are some ID's and stuff here that miss in the HTML, those are just wrappers for positioning.
As you see, I created an active
class in CSS for when someone clicks. The position set there is the colored one.
Now, when someone clicks an icon, I want it to see the active class, and change color. This is done by jQuery:
$("#setmale").click(function()
{
$('#registercontainer .submenu .male').addClass('active');
});
$("#setfemale").click(function()
{
$('#registercontainer .submenu .female').addClass('active');
});
But the stupid thing just won't work... Did I make any mistakes with the selector or anything?
Thanks.
To add a new class, we use jQuery addClass() method. The addClass() method is used to add more classes and their attributes to each selected element. It can also be used to change the property of the selected element.
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
I really easy solution to what you have is to just change your css to this;
#registercontainer .submenu .male:hover, #registercontainer .submenu .male.active {
background-position: -7px -397px;
}
#registercontainer .submenu .female:hover, #registercontainer .submenu .female.active {
background-position: -60px -397px;
}
Notice that the .male.active
and .female.active
are chained together. Read more about css chaining
Also a little improvement to your JS code would be to change your click code to just $(this).addClass('active');
as $(this)
is the element which raised the click event.
Your js is not at fault, ignore all the js answers sending you down a rabbit hole.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With