How to remove a class on second click in jQuery - javascript

Basically what I want to do is adding the .ani class to the clicked element and removing the .ani from all, but I also need to remove the .ani from the element which already have it on second click.
As you can see the regular add and removing is working fine but I can not remove the .ani on existing element. How can I fix this?
$(".list").on('click', function() {
$('.list').removeClass("ani");
if ($(this).hasClass('ani')) {
$(this).toggleClass("ani");
} else {
$(this).addClass("ani");
}
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>

It looks like you are over complicating this task. Take a look at the code below (posting only the JS as HTML and CSS are the same):
$(".list").on('click', function() {
$(this).toggleClass("ani").siblings().removeClass("ani");
});
A breakdown of what this does:
use toggleClass on the item clicked to add remove the class on the
item
get all siblings of the clicked item and remove the class from them
How this works:
The bit of code in the example above uses something called method chaining where you execute multiple methods on the same jQuery Object. This is possible because most jQuery methods return a jQuery Object, post-execution. This makes it easier and faster to run a bunch of operations on the same set of elements. One thing that you need to be mindful about when chaining is the sequence of method calls - changing the order of methods that you use may result in adverse effects (i.e: most traversal methods in jQuery returns a different set of elements).
Fiddle: http://jsfiddle.net/darshanags/kz2wdo09/

Check this one. Just update onclick method. All other code is the same. I posted one is single line code and one if-else code which is commented. You can use which one is more comfortable for you. You are first removing ani class that was a bug in your code.
$(".list").on('click', function() {
$(this).toggleClass("ani").siblings().removeClass("ani");
/*if($(this).hasClass("ani")){
$(".list").removeClass("ani");
} else {
$(".list").removeClass("ani");
$(this).addClass("ani");
}*/
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>

In this code:
$(".list").on('click', function() {
$('.list').removeClass("ani");
if ($(this).hasClass('ani')) {
$(this).toggleClass("ani");
} else {
$(this).addClass("ani");
}
});
You're removing the class of every .list element, therefore the $(this).hasClass('ani') will always be false (you just removed the ani class of every single .list element, including the clicked one), so the line $(this).addClass("ani") will always be executed.
The solution is simple. Check if the clicked element has the ani class and if so, remove it, otherwise add it:
$(".list").on('click', function() {
if ($(this).hasClass('ani')) {
$(this).removeClass("ani");
}
else {
$('.list').removeClass("ani");
$(this).addClass("ani");
}
});

you want to remove class ani on all the elements except the clicked one. You can use not()
$(".list").on('click', function(evt) {
$(".list").not($(evt.currentTarget)).removeClass("ani");
$(evt.currentTarget).toggleClass("ani");
});
.list {
height: 60px;
width: 160px;
background: yellow;
margin: 4px;
cursor: pointer;
}
.ani {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>
<div class="list"></div>

Related

Hover on two elements using jQuery

I have two <div> elements attached to each other, I mean there is no space between them.
<div id="box1">1</div>
<div id="box2">2</div>
And I have this jQuery code:
$('#box1 , #box2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
My problem is when I move the mouse between box1 and box2, I still get on console log "Not".
I want those divs to be considered as one element so when I move the mouse between them I don't get on console log "Not".
Thanks in advance!
I want those divs to be considered as one element
Well, quite simply, they aren't. And they can't be. That's not how HTML and CSS works.
The hover event is triggered one for each individual element bound to the event handler. And every time you leave one of those elements it will print the "not" output as per your instructions.
There is no "fix" for this in the exact way you described, but there are alternative approaches. An obvious solution is to wrap them both in an outer div and bind the hover event to that instead. Then the whole area will be considered as one element (because it literally is). Demo:
$('#boxcontainer').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
#boxcontainer {
border: solid 1px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxcontainer">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
friend check the code below. I think it will work for you. As you have dai you have an absolute position div you must need a parent div and the parent div position must be relative. For doing that you have to add just a simple CSS code position: relative;. You also need to do some changes to your jquery code. You can just hover on the parent div and it will do your work. Hope this code will help you.
//Box 1 Demo
$('#boxParrent1').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
//Box 2 Demo
$('#boxParrent2').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});
/*Main Code that are needed*/
#boxParrent1, #boxParrent2 {
position: relative;
}
/*Codes Just used to give you a demo*/
#boxParrent1, #boxParrent2{
display: flex;
margin-bottom: 50px;
border: 1px solid #000;
}
#boxParrent1{
width: 200px;
}
#boxParrent2{
width: 210px;
}
#box1, #box2, #box3, #box4{
background: tomato;
width: 100px;
height: 100px;
display: grid;
justify-content: center;
align-items: center;
font-family: Arial;
font-size: 50px;
color: #fff;
cursor: pointer;
}
#box2, #box4{
position:absolute;
top: 0;
left:100px;
background: #02dce6;
}
#box4{
left:110px;
background: #02dce6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxParrent1">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
<div id="boxParrent2">
<div id="box3">3</div>
<div id="box4">4</div>
</div>
Try to place your 2 div's in one super div
<div id="super">
<div id="box1">1</div>
<div id="box2">2</div>
</div>
$('#super').hover(function() {
console.log("Hovered")
}, function() {
console.log("Not")
});

Selector for parent body from popup

I have a situation where I need to apply Styles on a POPUP based on if "Opener window" of that POP has a style class defined on it.
<html>
<body class="myClass">
<input type="button" onClick="Open('xyz.html')"/>
</body>
</html>
Now on xyz.html I want to have a CSS selector which can toggle some style based on if parent.html has class="myClass".
Is it possible without Jquery?
If not: what alternatives I have for this including Jquery and Javascript?
Please note: parent.html is opening xyz.html they are both separate windows.
You don't need to use jQuery to check it. You can make use of simple CSS for it. Check the code below. Here, if container has the class my-class. The property of background-color will be applied to the popup. Otherwise, it won't. Check the code and try using the same with and without the my-class in the container.
$('button').on('click', function() {
$('.popup').toggleClass('active')
})
.popup {
padding: 10px;
border: 1px solid #ddd;
opacity: 0;
transition: all 0.8s ease;
}
.popup.active {
opacity: 1;
}
.container.my-class .popup {
background-color: red;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container my-class">
<button>Click</button>
<div class="popup"> HAI </div>
</div>

Javascript removeClass() issue

Here is the css code :
.big-square {
position:relative;
height:768px;
width:768px;
border:1px solid black;
background-color:#007da9;
text-align:center;
display:table-cell;
-webkit-transition:all 0.3s linear;
}
and here the html:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css">
<script>
function showmenu() {
$(document).ready(function() {
$("#big-square").removeClass("big-square");
});
}
</script>
</head>
<body>
<div id="big-square" onclick="showmenu();" class="big-square">1</div>
<div id="big-square" onclick="showmenu();" class="big-square">2</div>
The problem is when I click on anyone of square, just the first dissapear and I want to make it dissapear separately. For example, if I click on the 2nd square, just the second squuare dissapear.
id must be unique in the whole DOM. (and the relevant functions return only the first one)
What you want is
$(document).ready(function() {
$(".big-square").on('click', function() {
$(this).removeClass("big-square");
});
});
.big-square {
position: relative;
height: 768px;
width: 768px;
border: 1px solid black;
background-color: #007da9;
text-align: center;
display: table-cell;
-webkit-transition: all 0.3s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="big-square">1</div>
<div class="big-square">2</div>
It is illegal HTML to have id's not be unique. Use a class instead if you plan to have 2 or more elements of similar 'stuff'. Then, you shouldn't nest the ready statement in a function. Next, you shouldn't use onclick, instead opting to listen to the event click. Additionally, the css .class does not match an id of your html. Finally to target 1 item only, I would use the jQuery object $(this).
So, all that said, I would re-write your code as:
<script>
$(document).ready(function() {
$(".big-square").click(function() {
$(this).removeClass("big-square");
});
});
</script>
</head>
<body>
<div class="big-square" id="square1">1</div>
<div class="big-square" id="square2">2</div>
That's newbie coding. Let's try to fix it:
1 - Different id's for each element (as user Vic pointed out already)
2 - $(document).ready doesn't need to be nested
3 - onclick="showmenu();" is completely unnecesary and including scripts in the html is bad practice in modern web development
I won't post any code because I see you already have answers with code :)

how to make an image work as a check box?

I am working on phone-gap application in dream-weaver
I have 2 divs .pics and .cover
<div class="pics">
<div class="cover"></div>
</div>
the main idea is to change the colour of the cover div and toggle a JS variable between true and false
var checked=false;
$('.pics').click(function(){
CheckToggle();
});
function CheckToggle(){
if(checked==false){
checked=true;
$('.cover').css({"background":"rgba(255,255,255,.5)"});
}
else
checked=false;
}
I click on .pics and nothing happens
I think there is an error in the jquery code
This is what I used after all
$(function(){
$( "#item1" ).bind( "tap", PicCheck );
var checked;
var choosen="#item1";
checked=$(choosen).attr('pcheck');
function PicCheck( event ){
if(checked=="false"){
$(choosen).toggleClass("selected");
checked="true";
}
else if(checked=="true"){
$(choosen).toggleClass("selected");
checked="false";
}
$(choosen).attr('pcheck',checked);
}
});
With some css you can implement a checkbox and radio buttons with pictures. Try this :
<div>
<input id="input-1" class="img-checkbox" type="radio" name="selectTipo">
<label for="input-1" class="">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/128px-HTML5_logo_and_wordmark.svg.png">
</label>
<input class="img-checkbox" type="radio" id="input-2" name="selectTipo">
<label for="input-2">
<img src="http://www.javatpoint.com/images/javascript/javascript_logo.png">
</label>
And in your css :
input.img-checkbox[type=radio], input.img-checkbox[type=checkbox] {
display: none;
}
img{
height:100px;
}
input.img-checkbox[type=radio]+label, input.img-checkbox[type=checkbox]+label {
border: 10px solid transparent;
display: inline-block;
border-radius: 10px;
}
input.img-checkbox[type=radio]:checked+label, input.img-checkbox[type=checkbox]:checked+label {
border: 10px solid #C6ECED;
display: inline-block;
}
See the result in the follow jsfiddle
I'd skip the Javascript and use a label element and the :checked selector.
#example {
visibility: hidden;
width: 0;
}
label {
color: purple;
}
#example:checked + label {
background-color: red;
color: white;
}
The HTML would be like this:
<input id="example" type="checkbox" name="example" value="true">
<label for="example">Example</label>
With this approach you wouldn't need to worry about tracking the checked variable and you can just figure it out normally.
Here's a demo: http://jsbin.com/cirali/1/edit?html,css,output
It is usually most convenient to use additional class for your purpose.
Here is a simple example:
var checked = false;
$('.pics').click(function() {
CheckToggle();
});
function CheckToggle() {
$('.cover').toggleClass('selected');
checked = $('.cover').hasClass('selected');
}
.cover {
background: red;
}
.cover.selected {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pics">
<div class="cover">test</div>
</div>
Edit:
Since you are using jQuery mobie, you might want to try the vclick or tap events instead of the regular click event.
Depending on how you have the elements styled, it might be better to put the action on the .cover element... If the child element .cover is the exact same height and width of the parent element .pics you wont be able to click on .pics

How to find all divs with specific ID using jQuery regular expression

In my document I've got several divs with ID beginning with letter "p" and then any number. I'd like to find them all using jQuery regular expression pattern and then add class to them. Can you help me fix this snippet? Thanks.
$(function(){
var pattern = "#p\d+";
$(pattern).addClass(".red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="p46"></div>
<div id="p124"></div>
Sure, you can use the filter method to apply any specific logic you need:
$(function(){
$("div")
.filter(function() { return /^p\d+$/.test(this.id); })
.addClass("red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="nomatch"></div>
<div id="p124"></div>
You could try
$("div").filter(function(i,e){return e.match(/^p\d+$/)!=null;}).addClass("red")
It basically finds all divs, then filters out those that don't match the regular expression and adds the class to the remaining tags. (I have not tested this code.)
You can add classes this way:
$("div[id^='p']").addClass(".red");

Categories

Resources