Toggle multiple divs one at a time with 1 button using Jquery - javascript

I have four divs which i want to toggle one at a time with a single button. I want to toggle them one after the other and not randomly. I have tried something like below.
$(document).ready(function() {
$('#toggle').click(function() {
$('#1').hide();
});
$('#toggle').click(function() {
$('#2').hide();
});
$('#toggle').click(function() {
$('#3').hide();
});
$('#toggle').click(function() {
$('#4').hide();
});
});
.divs {
border: 1px solid;
height: 30px;
}
<div id='1' class='divs'></div>
<div id='2' class='divs'></div>
<div id='3' class='divs'></div>
<div id='4' class='divs'></div>
<button id='toggle'>
toggle
</button>

Save the state on each click.
$(document).ready(function() {
var state = 1;
$('#toggle').click(function() {
if(state==1){
$('#1').hide();
state=2;
}
else if(state==2){
$('#2').hide();
state=3;
}
else if(state==3){
$('#3').hide();
state=4;
}
else if(state==4){
$('#4').hide();
state=1; //back to state
}
});

$(document).ready(function() {
$('#toggle').click(function() {
$('.divs:visible:first').hide();
});
});

Try this one
var count = 1;
$(document).ready(function () {
$('#toggle').click(function(){
$('.divs').show();
if(count == 4)
count = 1;
$('#' + count).hide();
count++;
});
});

First of all, keeping numeric ids is not good, so considering you will change them after wards, I am writing both the answers with numeric ids and without numeric ids.
With Numeric Ids, it is easy to do.
Suppose you have button to toggle the other four divs then it would look like this:
var state = 1;
$("#toggleButton").click(function(){
$("#"+state++).slideToggle();
if(state===5){state=1;}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id='1' >1</div>
<div id='2' >2</div>
<div id='3' >3</div>
<div id='4' >4</div>
<button id="toggleButton">
toggle
</button>
Now coming to the non numeric ids.
var state = 1;
$("#toggleButton").click(function(){
$("#div"+state++).slideToggle();
if(state===5){state=1;}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id='div1' >1</div>
<div id='div2' >2</div>
<div id='div3' >3</div>
<div id='div4' >4</div>
<button id="toggleButton">
toggle
</button>
FYI:In my opinion you should not use numeric ids.
Further adding more in to the code.
If you don't know how many div would be there but you are having a clear cut rule that the div's follow the sequence whether or not they are having numeric/non numeric ids then you can change the code slightly to incorporate that as well like this.
var state = 1;//first button id to be toggled
var total = 4;//this will be the total number of divs to be handled by the button
$("#toggleButton").click(function(){
$("#"+state++).slideToggle();
if(state===(total+1)){state=1;}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id='1' >1</div>
<div id='2' >2</div>
<div id='3' >3</div>
<div id='4' >4</div>
<button id="toggleButton">
toggle
</button>
Happy coding.

Use class instead of Id for using many times
var i = 1;
$('#toggle').click(function(){
$('.divs').show();
$('#' + i).hide();
i++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='1' class='divs'>dsgsdg</div>
<div id='2' class='divs'>64636</div>
<div id='3' class='divs'>46y</div>
<div id='4' class='divs'>4373477</div>
<button id='toggle'>
toggle
</button>

loop through each element and use toggle. This gives the effect that you desire.
$('button').click(function(){
$('.divs').filter(function(index,item){
$(item).toggle('slow')
})
})
Have a look at this demo -
https://jsfiddle.net/ukw5wcmt/

var i = 1;
$('#toggle').click(function(){
$('.divs').show();
$('#' + i).hide();
if(i==4)
{
i=1;
}else{
i++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='1' class='divs'>dsgsdg</div>
<div id='2' class='divs'>64636</div>
<div id='3' class='divs'>46y</div>
<div id='4' class='divs'>4373477</div>
<button id='toggle'>
toggle
</button>
Try this

.hide{ display: none; }
$(document).ready(function(){
$(".click-btn").click(function(){
var fid = $(".hide:first").prop("id");
$("#"+fid).removeClass("hide");
});
$(".remove-tag").click(function(){
$(this).parent().addClass("hide");
});
});
<div id="cart-1" class="hide">
<div class="remove-tag">x</div>
<h5>1</h5>
</div>
<div id="cart-2" class="hide">
<div class="remove-tag">x</div>
<h5>2</h5>
</div>
<div id="cart-3" class="hide">
<div class="remove-tag">x</div>
<h5>3</h5>
</div>
<div id="cart-4" class="hide">
<div class="remove-tag">x</div>
<h5>4</h5>
</div>
<div id="cart-5" class="hide">
<div class="remove-tag">x</div>
<h5>5</h5>
</div>
<button class="click-btn">click</button>

Related

Add automatic refresh to a div with JS

The div works perfectly, but adding a new value to it results in NaN. But when updating the page, the div shows the updated value.
Would there be any way to add an automatic refresh to this div?
$(function () {
$(".but").on("click",function(e) {
e.preventDefault();
$(".content").hide();
$("#"+this.id+"div").show();
});
});
.content { display:none };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="but" type="button" id="Id">Load</button>
<div id="Iddiv" class="content">
<h2>content div</h2>
</div>
$(function () {
$(".but").on("click",function(e) {
if ($("h2")[0].innerHTML=='content div'){
$("h2")[0].innerHTML="";
}else {
$("h2")[0].innerHTML='content div';
}
});
});
.content { display:block };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="but" type="button" id="Id">Load</button>
<div id="Iddiv" class="content">
<h2></h2>
</div>
Given that hadent supplied where the new data comes from. Here are 2 examples.
Example one:
<button class="btn1" type="button" id="Id" data-newtxt="Example Text">Load</button>
<div id="section1">
<h2>content div</h2>
<span class="new-data"></span>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.btn1').click(function() {
$('.section1 .new-data').text( $(this).data('newtxt') );
})
});
</script>
Example two:
<button class="btn2" type="button" id="Id" data-newtxt="Example Text">Load</button>
<div class="hidden-div">Some example content</div>
<div id="section2">
<h2>content div</h2>
<span class="new-data"></span>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.btn2').click(function() {
$('.section2 .new-data').text( $('.hidden-div').text() );
})
});
</script>

Displaying elements based on search

I would like the .box elements to show/hide based on the words the user searches for, so for example if a user types in 'Title2 Title1' because those words exists inside box one and two they will remain visible with the renaming .box elements hiding. All the text within the .box elements needs to be searchable not just that in the .title element.
Below is how far I've got. It's almost there but it's not quite working as hoped.
Any help would be great.
Many thanks.
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
<script>
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')')) {
$(this).show();
} else {
$(this).hide();
}
});
});
} else {
$(".box").show();
}
});
</script>
You need to use a different search method. :contains does not work as you expect. Consider the following example.
$(function() {
function filter(e) {
var term = $(e.target).val();
if (term.length < 3) {
$(".box").show();
return;
}
$(".box").each(function(i, el) {
if ($(".content", el).text().indexOf(term) >= 0) {
$(el).show();
} else {
$(el).hide();
}
});
}
$("#search").keyup(filter);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">Box title one content</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">Box title two content</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">Box title three content</div>
</div>
So for example if on is entered, no filtering is performed. If one is entered, the script will look inside the content class of each box and if one is found in the text, it will be shown otherwise, it is hidden. If the User clears their search out, all items are shown.
Hide all box before iterate, then only show when match any words:
$("#search").on("input", function () {
var search = $(this).val();
if (search !== "") {
var searchArray = search.split(" ");
// Hide all .box
$(".box").each(function () {
$(this).hide();
})
searchArray.forEach(function(searchWord) {
$(".box").each(function () {
if($(this).is(':contains('+ searchWord +')') ) {
$(this).show();
}
});
});
} else {
$(".box").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder="Search" id="search" type="text" />
<div class="box">
<div class="title">Box Title1</div>
<div class="content">
Box title one content
</div>
</div>
<div class="box">
<div class="title">Box Title2</div>
<div class="content">
Box title two content
</div>
</div>
<div class="box">
<div class="title">Box Title3</div>
<div class="content">
Box title three content
</div>
</div>
Loop through all .boxs and using regex pattern matching, check either the title or content matches the search query. Show all matched boxes and hide all others
I have also fiddled it here
$("#search").on("input", function () {
var searchables=$('.box');
console.log(searchables)
var query=$(this).val();
searchables.each(function(i,item){
var title=$(item).find('.title').text();
var content=$(item).find('.content').text();
var rgx=new RegExp(query,'gi');
if(rgx.test(title) || rgx.test(content))
{
$(item).show();
}
else
{
$(item).hide();
}
})
})

Javascript function to rotate some div elements on page

I have some javascript function - shows me a popup with some texts. I try to rotate two "section" elements, but if I add to HTML one more section with class custom, the page shows only first element. Please, help me to add 1-2 more elements and to rotate it. The idea is to have 2 or more elements with class custom and to show it in random order, after last to stop. Thanks.
setInterval(function () {
$(".custom").stop().slideToggle('slow');
}, 2000);
$(".custom-close").click(function () {
$(".custom-social-proof").stop().slideToggle('slow');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="custom">
<div class="custom-notification">
<div class="custom-notification-container">
<div class="custom-notification-image-wrapper">
<img src="checkbox.png">
</div>
<div class="custom-notification-content-wrapper">
<p class="custom-notification-content">
Some Text
</p>
</div>
</div>
<div class="custom-close"></div>
</div>
</section>
Set section display none of page load instead of first section. Check below code of second section:
<section class="custom" style=" display:none">
<div class="custom-notification">
<div class="custom-notification-container">
<div class="custom-notification-image-wrapper">
<img src="checkbox.png">
</div>
<div class="custom-notification-content-wrapper">
<p class="custom-notification-content">
Mario<br>si kupi <b>2</b> matraka
<small>predi 1 chas</small>
</p>
</div>
</div>
<div class="custom-close"></div>
</div>
</section>
And you need to make modification in your jQuery code as below:
setInterval(function () {
var sectionShown = 0;
var sectionNotShown = 0;
$(".custom").each(function(i){
if ($(this).css("display") == "block") {
sectionShown = 1;
$(this).slideToggle('slow');
} else {
if (sectionShown == 1) {
$(this).slideToggle('slow');
sectionShown = 0;
sectionNotShown = 1;
}
}
});
if (sectionNotShown == 0) {
$(".custom:first").slideToggle('slow');
}
}, 2000);
Hope it helps you.

How do I create a show/hide loop in jQuery?

Here is my HTML with 3 questions and 3 answers:
<div class="faq-carousel">
<div class="all-questions question1">
<h4>Question 1</h4>
</div>
<div class="all-questions question2">
<h4>Question 2</h4>
</div>
<div class="all-questions question3">
<h4>Question 3</h4>
</div>
<div class=" all-answers answer1">
<p>Answer 1</p>
</div>
<div class=" all-answers answer2">
<p>Answer 2</p>
</div>
<div class=" all-answers answer3">
<p>Answer 3</p>
</div>
Here is my jQuery that shows/hides the 3 questions and answers:
jQuery(document).ready(function () {
"use strict";
jQuery(".all-answers").hide();
jQuery(".answer1").show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(".question1").addClass("highlighted");
var slideNumber = 1;
jQuery(".question1").click(function () {
jQuery(".all-answers").hide();
jQuery(".answer1").show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(".question1").addClass("highlighted");
slideNumber = 1;
});
jQuery(".question2").click(function () {
jQuery(".all-answers").hide();
jQuery(".answer2").show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(".question2").addClass("highlighted");
slideNumber = 2;
});
jQuery(".question3").click(function () {
jQuery(".all-answers").hide();
jQuery(".answer3").show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(".question3").addClass("highlighted");
slideNumber = 3;
}); });
How can I change the jQuery so that I can add more Q and A's to the HMTL without having to add more jQuery?
Many thanks!
The process you're trying to achieve here is to 'DRY' up your code, in other words, Don't Repeat Yourself.
To achieve what you need you can use common classes on the questions and answers, then relate the two together by their indexes, something like this:
"use strict";
jQuery(document).ready(function($) {
$('.question').click(function() {
$('.question').removeClass('highlighted');
var index = $(this).addClass('highlighted').index();
$('.answer').hide().eq(index).show();
});
});
.answer { display: block; }
.answer ~ .answer { display: none; }
.highlighted { background-color: #CC0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq-carousel">
<div class="question">
<h4>Question 1</h4>
</div>
<div class="question">
<h4>Question 2</h4>
</div>
<div class="question">
<h4>Question 3</h4>
</div>
<div class="answer">
<p>Answer 1</p>
</div>
<div class="answer">
<p>Answer 2</p>
</div>
<div class="answer">
<p>Answer 3</p>
</div>
</div>
Alternatively, if you want to explicitly link the elements together, due to HTML structure restrictions for example, then you can use data attributes to specify the relationships between elements:
"use strict";
jQuery(document).ready(function($) {
$('.question').click(function() {
$('.question').removeClass('highlighted');
var target = $(this).addClass('highlighted').data('target');
$('.answer').hide().filter(target).show();
});
});
.answer { display: block; }
.answer ~ .answer { display: none; }
.highlighted { background-color: #CC0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq-carousel">
<div class="question" data-target="#answer-01">
<h4>Question 1</h4>
</div>
<div class="question" data-target="#answer-02">
<h4>Question 2</h4>
</div>
<div class="question" data-target="#answer-03">
<h4>Question 3</h4>
</div>
<div class="answer" id="answer-01">
<p>Answer 1</p>
</div>
<div class="answer" id="answer-02">
<p>Answer 2</p>
</div>
<div class="answer" id="answer-03">
<p>Answer 3</p>
</div>
</div>
Use a data attribute with the answer id.
Add the eventListener to all questions at once using jQuery(".all-questions").click
use jQuery('.answer'+jQuery(this).data('answer')).show(); to show current answer.
this will use current element.
use jQuery(this).addClass("highlighted"); to add the class to current element
To add the slide number, use slideNumber = jQuery(this).data('answer');
jQuery(document).ready(function() {
"use strict";
jQuery(".all-answers").hide();
jQuery(".answer1").show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(".question1").addClass("highlighted");
var slideNumber = 1;
jQuery(".all-questions").click(function() {
jQuery(".all-answers").hide();
jQuery('.answer'+jQuery(this).data('answer')).show();
jQuery(".all-questions").removeClass("highlighted");
jQuery(this).addClass("highlighted");
slideNumber = jQuery(this).data('answer');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="faq-carousel">
<div data-answer="1" class="all-questions question1">
<h4>Question 1</h4>
</div>
<div data-answer="2" class="all-questions question2">
<h4>Question 2</h4>
</div>
<div data-answer="3" class="all-questions question3">
<h4>Question 3</h4>
</div>
<div class=" all-answers answer1">
<p>Answer 1</p>
</div>
<div class=" all-answers answer2">
<p>Answer 2</p>
</div>
<div class=" all-answers answer3">
<p>Answer 3</p>
</div>
Give all questions and answer elements a data-number attribute with the correct number then use
$(".all-questions").click(function() {
$(".all-questions").hide();
var slideNumber = $(this).data("number");
$(".answer"+slideNumber).show();
$(".all-questions").removeClass("highlighted");
$(this).addClass("highlighted");
}
With no changes to the HTML, something like this should do it :
jQuery(function ($) {
"use strict";
$('.all-questions').on('click', function() {
$('.all-answers').hide().filter('.answer' + $(this).index()).show();
$('.all-questions').removeClass('highlighted').filter(this).addClass('highlighted');
});
$(".question1").trigger('click');
});
Try this one. Very simple. The trick I used is to associated every question class name with it's answers class name. For instance, if Question 1 class name is question1, its answer class name is question1_answer. After that let the magic happen (you can add your style however you want. Just copy/paste and run that code an see what it does.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
function myFunction(classname){
var answerClassName = "." + classname + '_answer';
$(answerClassName).show();
//Hide all other answers
var otherAnswers = document.body.getElementsByTagName("div");
var l = otherAnswers.length;
for(i=0 ; i<l ;i++){
if(otherAnswers[i].className == classname){
//do nothing
}else{
var otherAnswersClassName = "." + otherAnswers[i].className + '_answer';
jQuery(otherAnswersClassName).hide();
}
}
}
</script>
</head>
<body>
<div class="question1" onclick="myFunction(this.className)">
<h4>Question 1</h4>
</div>
<div class="question1_answer">
<p>Answer 1</p>
</div>
<div class="question2" onclick="myFunction(this.className)">
<h4>Question 2</h4>
</div>
<div class="question2_answer">
<p>Answer 2</p>
</div>
</body>
</html>

How can I make jquery script shorter?

I have got following code (i shorted it to make it more readable)
And I would like to ask if it is possible to do not write almost the same code for every button? How can I do it the easiest way? I have got 6 buttons and code would be quite long.
<script>
$(document).ready(function(){
$("#option1").click(function(){
if($(".option1").is(":visible")){
$(".option1").hide("slow",function(){});
}
else{
$(".option2, .option3").hide("slow",function(){});
$(".option1").show("slow",function(){});
}
});
$("#option2").click(function(){
if($(".option2").is(":visible")){
$(".option2").hide("slow",function(){});
}
else{
$(".option1, .option3").hide("slow",function(){});
$(".option2").show("slow",function(){});
}
});
$("#option3").click(function(){
if($(".option3").is(":visible")){
$(".option3").hide("slow",function(){});
}
else{
$(".option1, .option2").hide("slow",function(){});
$(".option3").show("slow",function(){});
}
});
});
</script>
<body>
<div class="containter">
<div class="row">
<div class="col-md-4">
<button type="button" id="option1" class="btn btn-primary">Button1 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option2" class="btn btn-primary">Button2 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option3" class="btn btn-primary">Button3 >></button>
</div>
</div>
</div>
</body>
Without the need to change much of your html, add a common class option to all your option1, option2, ... :
<div class ="option option1">a</div>
<div class ="option option2">b</div>
<div class ="option option3">c</div>
and then you can use this below:
Array.from(document.getElementsByTagName('button')).forEach(function(btn){
btn.addEventListener('click', function(e){
if($("." + e.target.id).is(":visible")){
$("." + e.target.id).hide("slow",function(){});
}
else{
$(".option").hide("slow",function(){});
$("." + e.target.id).show("slow",function(){});
}
});
});
DEMO
You can reduce the code to just one click listener. Try this:
<script>
$(document).ready(function() {
$(".btn-primary").click(function() {
var option = $(this).data("option");
if ($(".option." + option).is(":visible")) {
$(".option." + option).hide("slow", function() {});
} else {
$(".option").not("." + option).hide("slow", function() {});
$(".option." + option).show("slow", function() {});
}
});
});
</script>
<body>
<div class="containter">
<div class="row">
<div class="col-md-4">
<button type="button" id="option1" data-option="option1" class="btn btn-primary">Button1 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option2" data-option="option2" class="btn btn-primary">Button2 >></button>
</div>
<div class="col-md-4">
<button type="button" id="option3" data-option="option3" class="btn btn-primary">Button3 >></button>
</div>
</div>
</div>
<!-- common class option added -->
<div class="options">
<div class="option option1"></div>
<div class="option option2"></div>
<div class="option option3"></div>
</div>
</body>
I added a common class to all the options, and a data-option attribute to your buttons.
You don't need to check to see whether the current button is visible. It's visible because it was just clicked on.
All you need to do is show the other buttons that weren't clicked on and hide the one that was. To do this, assign the same class to all 3 buttons. In the example below, I added the class "myBtn" to all 3 buttons.
$(".myBtn").click(function () {
var id = $(this).attr('id');
$(".myBtn:not(#"+id+")").show("slow", function () {});
$(this).hide();
});
JSFiddle demo.

Categories