only one element at time can be "toggleClass"-ed in jQuery - javascript

How I am able to toggleClass on elements, but only one can be "toggled" at time.
There is solution (by adding another for loop to disable effect), but in pureJS and I need help to get this work in jQuery.
var elements = document.querySelectorAll("#box");
for ( var i = 0; i < elements.length; i++ ) (function(i){
elements[i].onclick = function() {
for (var j = 0; j < elements.length; j++) {
elements[j].style.border = '';
elements[j].innerHTML = '';
}
elements[i].style.border = "10px solid red";
elements[i].innerHTML = "selected";
};
})(i);
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>
And here is jQuery function. In-short, I need that only one box can be red at time and when another is clicked it disable selected one. Exactly like one above in javascript.
$("div#box").click(function(){
$(this).toggleClass("red");
});
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>

The usual way to do this is to remove the class on all of the other possible 'toggles' before applying the class to the newly selected one, like this:
var boxes = $('div.box');
boxes.click(function(){
boxes.removeClass('red');
$(this).addClass('red');
});
(You should use a class, not an ID any time you have more than one element to apply it to (so I've used .box, not #box).
Another important point is to select the boxes only once, and store them in a variable outside of the click handler. That way, you're not always re-selecting them on every click.

the this, refers to the current clicked element.
you will need to apply it to all the nav items such as below.
var
$boxes = $("div#box").click(function(){
$boxes.removeClass("red");
$(this).addClass("red");
});
body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>

Like previously said use a class instead of an ID. You can use the .not() jQuery method to achieve this.
Note: The difference between Beejamin's answer and mine is that in this one you can toggle the red class clicking the same square again while also removing siblings selection.
var box = $(".box");
box.click(function() {
$(this).toggleClass("red");
box.not(this).removeClass("red");
});
body {
background-color: black;
}
.box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Related

How can I remove class when click the same button

Please see code below:
const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
sectionBtn.addEventListener("click", (btns)=> {
// console.log(sectionIconHover)
const containerTarget = btns.currentTarget.parentElement.children[1]
const containerHoverTarget = btns.currentTarget.parentElement.children[0]
sectionContainer.forEach(items => {
if(items !== containerTarget) {
items.classList.remove("show")
// itemHover.classList.remove("rb")
}
})
sectionIconHover.forEach(itemHover => {
if(itemHover !== containerHoverTarget) {
itemHover.classList.remove("rb")
}
})
containerTarget.classList.toggle("show")
containerHoverTarget.classList.add("rb")
})
})
.nk-section-icons {
height: 30px;
min-width: 30px;
width: 30px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 3px;
background: yellow;
margin-bottom: 5px;
}
.nk-section-icons.rb {
background: black;
}
.nk-sec-container {
width: 300px;
min-width: 300px;
height: 100%;
background: red;
position: absolute;
z-index: 11;
box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
border-radius: 6px;
left: 70px;
top: 0px;
}
.nk-sec-container.show {
background: green;
}
.nk-section-icons-container {
position: relative;
}
<div class="nk-section-l-icons">
<div class="nk-section-icons-container">
<div class="nk-section-icons fav" data-title="Favorites">btn</div>
<div class="nk-sec-container nk-sec-fav-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons recent" data-title="Recent">btn</div>
<div class="nk-sec-container nk-sec-recent-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons notifs" data-title="Notifications">btn</div>
<div class="nk-sec-container nk-sec-notif-c">
</div>
</div>
</div>
Hello guys, can you please see my code? Currently, it's working fine when I click the button it's working the classes are moved when I click any of the buttons. However, if I tried clicking the same button again the class rb is not removed but the show class is removed. Can you please help me with how can I fix this? Thanks
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if($("p").hasClass("main"))
{
$("p").toggleClass("main1");
}
else
{
$("p").toggleClass("main");
}
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
.main1 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>
</body>
</html>
Use toggling: Toggle between adding and removing the "main" class name for all elements
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

JQuery hide multiple div of similar id when clicked outside

I want to hide all the div with similar id if not clicked on any of those div's. In my code it is working only for the first div since I have use index[0] to fetch the id. I want to generalize it to work for all the id.
Here is the code:
$(window).click(function(e) {
if (e.target.id != $('[id^=div_]')[0].id) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>
FIDDLE
The simple solution here is to use a common class on all the elements. You can then use is() to determine if e.target was one of those elements and hide/show them as needed. Try this:
$(window).click(function(e) {
if (!$(e.target).is('.div')) {
$('.div').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
I cannot make any changes in HTML like adding classes
In that case you can check the id of the clicked element to see if it begins with div_. If not, then hide all the divs, something like this:
$(window).click(function(e) {
if (e.target.id.indexOf('div_') != 0) {
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
Hey you can use this function
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
filter function will filter the selected div in list of div whoes id starts with div
$(window).click(function(e) {
if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
$('[id^=div_]').hide();
}
});
div {
height: 150px;
width: 150px;
display: inline-block;
background: green;
margin: 10px;
color: #fff;
text-align: center;
line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>

Toggle "addClass" at 3 divs successively

This is my html:
<div class="button"></div>
<div class="wrapper>
<div class="something">Hello</div>
<div class="box one">Box 1</div>
<div class="box two">Box 2</div>
<div class="box three">Box 3</div>
</div>
By clicking the div "button", I want to add the class "active" to the first div with class name "box". If I clicking the button again, I want to remove the class "active" from box 1 and add it to box 2. Aso.
Later, if box 3 has the added class name "active" and I press the div "button" again, it should start from the beginning.
I try something like this, but it fails:
$(".button").click(function() {
$(this).find(".wrapper").add(".box").toggleClass("active");
});
You'll need to use css :eq() selector or .eq() on jquery
$(document).ready(function(){
var index = 0; // define index for the first box
$('.button').on('click',function(){
$('.wrapper .box').removeClass('active'); // remove class active from all box divs
$('.wrapper .box:eq('+index+')').addClass('active'); // add class active to the box index we need
index = (index < $('.wrapper .box').length - 1) ? index +1 : 0; // if index = the number of box divs add + 1 if not return it back to 0
}).click(); // if you need to run it onload add .click()
});
.active{
background : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click</div>
<div class="wrapper">
<div class="something">Hello</div>
<div class="box one">Box 1</div>
<div class="box two">Box 2</div>
<div class="box three">Box 3</div>
</div>
You can try something like this:
jQuery(".button").click(function(){
var active = jQuery(".wrapper").children(".active").first();
if (!active.length)
jQuery(".wrapper").children(":first").addClass("active");
else{
active.removeClass("active");
if (active[0] != jQuery(".wrapper").children(":last")[0])
active.next().addClass("active");
else
jQuery(".wrapper").children(":first").addClass("active");
}
});
.button {
width: 150px;
height: 50px;
cursor: pointer;
background-color: blue;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
border-style: solid;
border-width: 0.5px;
border-radius: 9px;
position: relative;
left: 30%;
}
.wrapper {
margin-top: 20px;
margin-left: 30px;
background-color: white;
width: 450px;
height: 550;
text-align: center;
border-style: dashed;
}
.active {
background-color: grey;
}
.something {
margin-bottom: 8px;
margin-top: 8px;
}
.box {
margin-bottom: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">
<p>Press Me</p>
</div>
<div class="wrapper">
<div class="something">Hello</div>
<div class="box one">Box 1</div>
<div class="box two">Box 2</div>
<div class="box three">Box 3</div>
</div>
Some fun with generator functions :)
let box = 0;
$('.button').on('click', function() {
const boxes = document.querySelectorAll('.box'); // get all boxes
let iter = activateBox(box, boxes); // create itarator to go over boxes
$('.box').removeClass('active'); // remove any active class from all boxes
iter.next(box++).value.classList.add('active'); // add active class to the next box in line
if (box === boxes.length) box = 0; // reset counter if last box reached
});
function* activateBox(i, boxes) {
yield boxes[i];
}
body {
font-family: 'Arial', sans-serif;
}
.button {
display: inline-block;
padding: 8px;
border: 2px solid lightblue;
border-radius: 4px;
color: #444;
cursor: pointer;
transition: background .15s ease-out;
}
.button:hover {
background: lightblue;
color: #FFF;
}
.box {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 100px;
background: #FFF;
margin: 8px 0;
border: 2px solid lightblue;
border-radius: 4px;
}
.box.active {
background: lightblue;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Apply Active</div>
<div class="wrapper">
<div class="box one">Box 1</div>
<div class="box two">Box 2</div>
<div class="box three">Box 3</div>
</div>

How to make slideToggle dynamic in JQuery

I have a page where multiple div and within each div there is a option to click and toggle the information, I am able to create by defining different IDs of DIV but I think that can be done somehow dynamically, here is what I have created in JSFiddle
CSS
.boxwrap {
float: left;
width: 200px;
height: 250px;
border: 1px solid #ccc;
margin: 0 5px 0 0;
text-align: center;
box-sizing: border-box;
padding: 10px;
}
.boxwrap_inner {
float: left;
width: 100%;
background: #ddd;
padding: 5px 0;
text-align: center;
}
.noDisplay {
display: none;
}
HTML
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content1">
Content goes here
</div>
</div>
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content2">
Content goes here
</div>
</div>
JQuery
$('#button1').click(function () {
$("#content1").slideToggle(200);
});
$('#button2').click(function () {
$("#content2").slideToggle(200);
});
Check this:
$('.boxwrap > a').click(function () {
$(this).next().slideToggle(200);
});
.boxwrap {
float: left;
width: 200px;
height: 250px;
border: 1px solid #ccc;
margin: 0 5px 0 0;
text-align: center;
box-sizing: border-box;
padding: 10px;
}
.boxwrap_inner {
float: left;
width: 100%;
background: #ddd;
padding: 5px 0;
text-align: center;
}
.noDisplay {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content1">
Content goes here
</div>
</div>
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content2">
Content goes here
</div>
</div>
The previous answers rely on the fact that the DOM is going to remain the same and the next() element after the button will always be the content div.
For a more robust solution, I would add a class to the buttons in the boxwrap(i.e. .boxbtn) and a class to the content divs (i.e. boxcontent) and then I would do something like the following:
$('.boxbtn').click(function () {
$(this).closest('.boxwrap')..find('.boxcontent').slideToggle(200);
});
Try this way,
It's better to specify the element with it's parent on which you're calling a click event.
$('.boxwrap > a').click(function(){
$(this).next('div').slideToggle(200);
});
Here with 2 options
using relative attribute value
using finding relative don element
/*$('.toggle_link').click(function () {
$($(this).data('toggle')).slideToggle(200);
});
OR
*/
$('.toggle_link').click(function () {
$(this).parent().find('.noDisplay').slideToggle(200);
});
.boxwrap{float:left; width:200px; height:250px; border:1px solid #ccc; margin:0 5px 0 0; text-align:center; box-sizing:border-box; padding:10px;}
.boxwrap_inner{float:left; width:100%; background:#ddd; padding:5px 0; text-align:center;}
.noDisplay{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content1">
Content goes here
</div>
</div>
<div class="boxwrap">
Go
<div class="boxwrap_inner noDisplay" id="content2">
Content goes here
</div>
</div>

How to center all list's elements to parent div

I am going to add dynamically elements to my block of ul.
I would like to center all list's elements to parent div(brown boder).
For example,
if the resolution of the browser allows you to set two blocks in one row, I would like to center this row in relation to parent div.
I would be very graftefully.
Link to demo
myCode:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
var tab = [2,3,4,5,7,8,9,11,12,13,14,15];
$(document).ready(function(){
$('#godziny').on('click', '.godzina', function(){
//alert(this.attr('class'));
$('.yb').removeClass('yb');
$(this).addClass('yb');
});
$('#getElements').click(function() {
for(i = 0; i < tab.length; ++i) {
alert(tab[i]);
setTimeout(function(i){
$('#godziny').append('<li class="godzina">' + tab[i] + '</li>');
}, i*50);
}
});
});
</script>
<style>
#spisSalonow {
margin: 0 auto;
}
#spisSalonow > div {
padding-top: 15px;
color:red;
}
#wybor_terminu {
border: 1px solid brown;
}
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
border: 1px solid red;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
float: left;
cursor: pointer;
margin-right: 40px;
margin-top: 40px;
/*margin:auto;*/
/*
opacity: 0.4;
filter: alpha(opacity=40);
*/
}
.yb {
background: yellow;
}
</style>
</head>
<body>
<div id="wrapper">
<input type="button" value="get Elements" id="getElements"/>
<section id="content">
<div class="full">
<BR/>
<div id="wybor_terminu" class="center border" style="width: 70%; position: relative;">
<div style="text-align: center"><img src="https://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-05-24.png" alt="Left Arrow" /> <span id="day"> ANY DAY </span> <img src="http://cdn0.iconfinder.com/data/icons/slim-square-icons-basics/100/basics-06-24.png" alt="Right Arrow" /></div>
<ul id="godziny" style="margin-top: 25px;">
</ul>
</div>
</section>
</div>
</body>
</html>
You can use the CSS flexbox to achieve this. Here is a link to a complete guide on how to use flexbox. I hope this helps.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Add this lines:
CSS
#wybor_terminu ul {
list-style-type: none;
overflow: hidden;
/*NEW*/
padding: 0;
width: 100%;
}
#wybor_terminu ul li {
width: 200px;
height: 200px;
text-align: center;
color: blue;
border: 0.2em solid green;
/*float: left; You don't need this line*/
cursor: pointer;
/*NEW*/
margin:auto;
margin-top: 40px;
}
EDIT
This is only a quick solution with bootstrap maybe it could help you a little bit. jsfiddle
jQuery
In this line I added bootstrap classes:
$('#godziny').append('<li class="godzina col-sm-12 col-md-6">' + tab[i] + '</li>');
This code center your boxes (is not the best solution, but it works):
countBoxes = $('#godziny').width() / 200;
alignBoxes = ($('#godziny').width()-(200*parseInt(countBoxes)))/2;
if(countBoxes >= 2.65){
$('#godziny').css('margin-left', alignBoxes);
} else{
$('#godziny').css('margin-left', 0);
}
If you change the resolution of your screen, click the button to center your boxes again.

Categories