Toggle/add/remove class in Jquery not working as expected - javascript

In my code i have two boxes, i want when i click on the box it should gain some width and when i click on another box it should gain the width and remove the extra width from previous box. I have done this successfully but when i click the extra width box again it does not removing it's extra width.
$('.dos').click(function() {
$(this).toggleClass('clicked');
});
$('.dos').click(function() {
$('.dos').removeClass('clicked');
$(this).addClass('clicked');
});
#box {
width: 100px;
height: 100px;
border: 1px solid #ccc;
transition: width 1s;
}
#box.clicked {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" class="dos"></div>
<div id="box" class="dos"></div>
Just want toggle class should also work with addClass and removeClass
(Demo on jsfiddle.net)

Check the updated fiddle and try
$(this).toggleClass('clicked').siblings().removeClass('clicked');
Demo
$('.dos').click(function() {
$(this).toggleClass('clicked').siblings().removeClass('clicked');
});
#box {
width: 100px;
height: 100px;
border: 1px solid #ccc;
transition: width 1s;
}
#box.clicked {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" class="dos"></div>
<div id="box" class="dos"></div>

You don't need to play with adding/removing classes. Here is the new fiddle
Edit your jQuery code with this, I have just added a boolean variable:
var toggle = false;
$('.dos').click(function() {
toggle = !toggle;
if (toggle) {
$(this).toggleClass('clicked');
}
});
$('.dos').click(function() {
toggle = !toggle;
if (toggle) {
$('.dos').removeClass('clicked');
$(this).addClass('clicked');
}
});

You are removing the class from the clicked button as well, if you want to achieve it you'll need to ignore the one clicked while removing the class
$('.dos').click(function() {
$('.dos').not(this).removeClass('clicked');
$(this).toggleClass('clicked');
});

Solution is as below:
You was trying to toggle already toggled div. Plus always use unique ids in your code :)
$('.dos').click(function() {
var out = this;
$( ".dos" ).each(function( index ,element ) {
console.log(element);
if($(element).attr("id") != $(out).attr("id")){
$(this).removeClass('clicked');
}
});
$(this).toggleClass('clicked');
});

Related

jquery.hover() adds class and removes it immediatly

I cannot show any pen, I can just describe the bug. This is my javascript:
$(".vetrina-deluxe-info-container-front").hover(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
}, function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
On the first .hover() on any of these elements, the class is added and immediately removed. From the second time I hover everything works fine.
I've also tried this code:
$(".vetrina-deluxe-info-container-front").mouseover(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
});
$(".vetrina-deluxe-info-container-front").mouseleave(function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
It has the exact same behavior. I have also tried to change the .hover() div to see if anything changes but no. Any ideas or workaround?
I've tried in diferents elements.
$('.test').mouseover(function(e){
console.log('ON');
$(this).removeClass('blue');
$(this).addClass('red');
}).mouseout(function(e){
$(this).removeClass('red');
console.log('OUT');
$(this).addClass('blue');
});
$('#test').mouseenter(function(e){
console.log('IN');
$(this).removeClass('red');
$(this).addClass('yellow');
}).mouseleave(function(e){
$(this).removeClass('yellow');
$(this).removeClass('yellow');
console.log('OUT');
$(this).addClass('red');
});
.test{
width: 60%;
height: 60%;
margin: 10px auto;
}
.yellow{
background-color: yellow;
}
.red{
background-color: red;
}
.blue{
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="test yellow">
<p>TEST</p>
</div>
</html>
Your code will be like:
$(".vetrina-deluxe-info-container-front").mouseenter(function() {
$(this).closest('.js-in-viewport-hook').addClass("in-viewport");
}).mouseleave(function() {
$(this).closest('.js-in-viewport-hook').removeClass("in-viewport");
});
Did you try this code:
$(".vetrina-deluxe-info-container-front").hover(function() {
$(this).closest('.js-in-viewport-hook').toggleClass("in-viewport");
});
please check this i have added class on hover then i remove the class name when not hovered
<p>hover me.</p>
<script>
$("p").hover(function(){
$(this).css({"color":"blue"}).addClass('color-blue');
}, function(){
$("p").css({"color":"red"}).removeClass('color-blue');
});
</script>
https://jsfiddle.net/gapqc5wb/

How to make css class turn back to before on click css jquery

so I have a <div> with a blue background color,with a jquery onclick event that changes color of that div to red. I was wondering how I could go about making the div background color change back to blue when the button is clicked again & turn back to red if click again and like that?
You need This.
$(".yourDiv").click(function () {
$(this).toggleClass("red");
});
Your CSS
.yourDiv{ background-color: #1E90FF; }
.yourDiv.red { background-color:#FF0000; }
I'm not sure what do you exactly mean by clicking twice, so I've made two possible solutions for you.
First box changes it's background to blue on one click and changes back into black, when clicked twice (double click).
Second box changes it's background with every click, one time it's green and one time it's yellow.
var box = document.getElementById('box'),
box2 = document.getElementById('box2'),
bool = true;
box.addEventListener('click', function(){
this.style.background = 'blue';
});
box.addEventListener('dblclick', function(){
this.style.background = 'black';
});
box2.addEventListener('click', function(){
if (bool) {
this.style.background = 'yellow';
bool = false;
} else {
this.style.background = 'green';
bool = true;
}
});
#box {
height: 100px;
width: 100px;
background: black;
margin: 5px;
}
#box2 {
height: 100px;
width: 100px;
background: green;
margin: 5px;
}
<div id='box'></div>
<div id='box2'></div>
your gonig to need to share some code for a sample on how your problem would be solved. But the most common way would be to have your jquery onclick event check the color of the div using code similar to:
var theColorIs = $('a').css("backgroundColor");
then having it change colors based on what the color currently is
You can use pass an empty string to .css in jQuery, like .css('background-color', '');, to clear previous value.
Jquery has a method called toggleClass which is ideal for this. You should also look at the toggle method.
<style>
.blue{
background-color: blue;
}
.red{
background-color: red;
}
</style>
<div class="blue">
....
</div>
<script>
$( ".blue, .red" ).click(function() {
$( this ).toggleClass("blue");
$( this ).toggleClass("red");
});
</script>
p.s. im typing on a phone
No jQuery necessary, all you need to do is add some styling to a CSS class and add/remove the class via Vanilla JavaScript.
let body = document.querySelector('body'),
box = document.querySelectorAll('.box');
body.addEventListener('click', function(e) {
let cl = e.target.classList;
if (cl.contains('box'))
cl.toggle('active');
});
.box {
background: blue;
display: inline-block;
margin: 5px;
height: 2.5rem;
width: 2.5rem;
}
.active {
background: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
binds click event to the parent element (in this case the body). This is important because instead of creating 5 click functions for the browser to handle, there's only one
because the click is attached to the body element, we have to look at what the event target was of the click (what was actually clickeD) in order to determine if it was a box (or just a body). We can determine if it was a box by checking for the class.
If you want to explore this more, remove the if statement and re-run the code. Then click on the white space. You'll notice that because we were not looking for boxes, it'll add the active class to any element that was clicked.
For even shorter code you can remove replace the whole if block with cl.contains('box') && cl.toggle('active');, which says "if the element has a box class, then toggle the active class"

Make text fade in and stay visible until mouse leaves the container

I'm tying to make text fadeIn and stay visible while the mouse pointer is in the container and only when the mouse pointer leaves the designated area, only then must the text fadeOut but for some reason its not working, the text will fadeOut even when the mouse is inside the container.
I'm using Jquery lib 1.10.1 as well as Jquery ui 1.11.0
Here is the code:
HTML
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<div class="hold">
<div class="conti">
<div class="arrow-right"></div>
</div>
<div class="text-fade"></div>
</div>
CSS
.hold{
width: 142px;
background: yellow;
overflow: hidden;
padding:10px;
}
.conti{
width: 30px;
}
.arrow-right {
width: 0;
height: 0;
border-top: 20px solid transparent;
border-bottom: 20px solid transparent;
border-left: 20px solid green;
}
.text-fade{
display: none;
float: right;
margin-top:-30px;
margin-left: 10px;
margin-right:10px;
}
JS
$('.hold').mouseenter(function () {
$('.arrow-right').effect("bounce", { direction:'right', times:3 }, 700);
$('.text-fade').text("this is a test text").fadeIn(1000).css('display',"block");
});
$('.hold').mouseout(function () {
$('.text-fade').fadeOut(1000);
});
This is the link to my fiddle example
mouseout is triggered by children, use mouseleave instead
$('.hold').mouseenter(function () {
// var d = $('.arrow-right');
// d.effect("bounce", { direction:'right', times:3 }, 700);
$('.text-fade').text("this is a test text").fadeIn(1000);
});
$('.hold').mouseleave(function () {
$('.text-fade').fadeOut(1000);
});
JS fiddle updated
Put the text directly into ".text-fade" and give some transition to the ".text-fader" class. Then change the text color via JS.
Here's the code for changing from #FFFFFF to #000000 and back again:
$('.hold').mouseenter(function () {
$('.arrow-right').effect("bounce", { direction:'right', times:3 }, 700);
$('.text-fade').css('color', '#000000');
});
$('.hold').mouseout(function () {
$('.text-fade').css('color', '#FFFFFF');
});
You are using the wrong functions, its mouseenter() and mouseleave()
working fiddle here
your javascript
$('.hold').mouseenter(function () {
$('.text-fade').text("this is a test text");
$('.text-fade').fadeIn(1000);
$('.text-fade').show();
});
$('.hold').mouseleave(function () {
$('.text-fade').fadeOut(1000);
});
also that bounce function you had seems to cause some problems that I could not find out why so I removed it

Change background color and active div color

im building a navigation and i want to add some functions.
On click on a div the navigation background color fades then the active button fades the color but when i click on another menu button the color from the previous button is actually there ... i want that only the acutally button fades the color and the background from the navigation and the previous removes the color
$('.re').click(function() {
$('.re').removeClass('active');
$(this).addClass('active');
});
$("#home0").click(function() {
$("#navigation").stop().animate({"backgroundColor":"grey"}, 800);
$(".active").stop().animate({"backgroundColor":"green"}, 800);
});
$("#home1").click(function() {
$("#navigation").stop().animate({"backgroundColor":"black"}, 800);
$(".active").stop().animate({"backgroundColor":"green"}, 800);
});
$("#home2").click(function() {
$("#navigation").stop().animate({"backgroundColor":"grey"}, 800);
$(".active").stop().animate({"backgroundColor":"green"}, 800);
});
This is my Code but it doesn't work :/
EDIT: Here is my Fiddle: Fiddle Demo
Since you are changing the color with javascript instead of CSS you need to remove the style attribute together with the active class..
$('.re').removeClass('active').removeAttr('style');
Demo at http://jsfiddle.net/gaby/tqYrT/3/
But you should really handle this with CSS and transitions.. (see Using CSS transitions)
I suggest using CSS Transitions to animate changes to CSS. Here's an example:
HTML:
Here, I am storing the desired nav background color as a custom data attribute (data-navbg):
<div id="navigation">
<div class="box" data-navbg="gray"></div>
<div class="box" data-navbg="black"></div>
<div class="box" data-navbg="gray"></div>
<div class="box" data-navbg="black"></div>
<div class="box" data-navbg="gray"></div>
</div>
JQUERY:
Here, when clicking a box, all boxes are set to not active, the clicked box is set to active, and the nav background is set to the desired color specified by the navbg attribute of the clicked box.
$('.box').click(function () {
var navbg = $(this).data('navbg');
$('.box').removeClass('active');
$(this).addClass('active');
$('div#navigation').css('backgroundColor', navbg);
});
CSS:
Here, the first definition applies CSS transitions to both the nav and the boxes:
#navigation, .box {
-moz-transition:0.25s;
-webkit-transition:0.25s;
-o-transition:0.25s;
transition:0.25s;
}
#navigation {
background-color: black;
height:60px;
width: 600px;
margin: 0 auto;
}
.box {
width: 60px;
height: 60px;
float: left;
background-color: #787878;
margin-right: 5px;
cursor: pointer;
}
.box.active {
background-color: green;
}
Working Example (jsFiddle)

changing css background image in collapsible div using javascript/jQuery

I’m after a hand with a bit of JavaScript if possible, I’m working on a collapsible list using jQuery and want to change a background image in a css file dependent on the state of the list
This is the html for the div
<div class="collapse_div">
<div class="header_div">header text</div>
<div class="content_div">
Some text
</div>
<div class="header_div">another header</div>
<div class="content_div">
some more text
</div>
</div>
This is the .css that puts the image (expanded.gif) into the header div
.collapse_div{
margin: 0;
padding: 0;
width: 500px;
}
.header_div {
margin: 1px;
color: #000;
padding: 3px 10px;
cursor: pointer;
position: relative;
background: url(expanded.gif) no-repeat 95%;
background-color:#ccc;
}
.content_div {
padding: 5px 10px;
background-color:#fafafa;
}
And this is the javascript function that controls the expand/collapse when header_div is clicked
jQuery(document).ready(function() {
jQuery(".content_div").hide();
//toggle the componenet with class msg_body
jQuery(".header_div").click(function()
{
jQuery(this).next(".content_div").slideToggle(500);
});
});
I’ve played around with adding code to the .click(function) to try and change the background css tag in .header_div to another file (collapse.gif) but I can’t get it to work, so I thought I’d ask the experts as my javascript is really rusty
At the moment the collapse/expand of the div works fine having the background image change on click would really make it look good
You can have a class with the requried background set and apply that class conditionally. Try this
CSS
.header_div_collapsed {
background: url(collapse.gif) no-repeat 95% !important;
}
JS
jQuery(document).ready(function() {
jQuery(".content_div").hide();
//toggle the componenet with class msg_body
jQuery(".expand_div").click(function()
{
jQuery(this).next(".content_div").slideToggle(500, function(){
var $this = $(this);
if($this.is(':visible')){
$this.removeClass('header_div_collapsed');
}
else{
$this.addClass('header_div_collapsed');
}
});
});
});
Your script should be something like this,
jQuery(document).ready(function() {
jQuery(".content_div").hide();
//toggle the componenet with class msg_body
jQuery(".expand_div").click(function()
{
var elm = jQuery( this );
jQuery(this).next(".content_div").slideToggle(500, function(){
if(jQuery(this).is(":visible"))
jQuery(elm).css({"background-image" : "collapse.gif"});
else
jQuery(elm).css({"background-image" : "expand.gif"});
});
});
});
thanks to both the suggestions post below I managed to get this to work
firstly I added a whole new css function as just defining the background didn't work
.expand_div_collapsed {
margin: 1px;
color: #000;
padding: 3px 10px;
cursor: pointer;
position: relative;
background: url(collapsed.gif) no-repeat 95%;
background-color:#ccc;
}
then the JS was changed to this
jQuery(document).ready(function() {
jQuery(".content_div").hide();
//toggle the componenet with class msg_body
jQuery(".header_div").click(function()
{
var co = jQuery(this);
jQuery(this).next(".content_div").slideToggle(500, function(){
if(jQuery(this).is(':visible')){
jQuery(co).addClass('expand_div_collapsed');
}
else{
jQuery(co).removeClass('expand_div_collapsed');
}
});
});
});
the add and remove class calls had to be swapped around and I had to define the var co before the slideToggle call
but thanks to everyone who offered suggestions as I would have never got this to work otherwise

Categories