how to create a jQuery function with less code - javascript

I am trying to create a function in jquery. I have three boxes with three buttons. when I click a button then a box will display and other boxes will be hidden. same thing with the other button.
$("#one").click(function () {
$(".box1").show();
$(".box2").hide();
$(".box3").hide();
});
$("#two").click(function () {
$(".box2").show();
$(".box1").hide();
$(".box3").hide();
});
$("#three").click(function () {
$(".box3").show();
$(".box1").hide();
$(".box2").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1" style="display:none">box one</div>
<div class="box2" style="display:none">box Two</div>
<div class="box3" style="display:none">box Three</div>
<button id="one" type="button">One</button>
<button id="two" type="button">Two</button>
<button id="three" type="button">Three</button>
my question is that is there any way to achieve my goal without repeat the same code multiple times.

There is a much easer approach to this, You could use Attributes.
Have a look below.
$(".container button").click(function(){
var className = "."+ $(this).attr("target");
$(".container div").hide() // hide all divs
// now view the target one
$(className).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="box1" style="display:none">box one</div>
<div class="box2" style="display:none">box Two</div>
<div class="box3" style="display:none">box Three</div>
<button id="one" target="box1" type="button">One</button>
<button id="two" target="box2" type="button">Two</button>
<button id="three" target="box3" type="button">Three</button>
</div>

Here's a way that utilizes the ID of your buttons and the ID of your divs to make a dynamic function
$(".button").click(function(e) {
// set up the object to map stuff
let obj = {
'one': 'box1',
'two': 'box2',
'three': 'box3'
};
$(".box").hide();
$("." + obj[e.target.id]).show();
});
.box {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1 box">box one</div>
<div class="box2 box">box Two</div>
<div class="box3 box">box Three</div>
<button id="one" class='button' type="button">One</button>
<button id="two" class='button' type="button">Two</button>
<button id="three" class='button' type="button">Three</button>

When any button is clicked, hide all the messages. Then just show the message who's index within its class matches the index of the button within its group.
$("button").click(function (event) {
// Hide all the messages
$(".box").each(function(index, box){
$(box).hide();
});
// Show just the message that applies
$($(".box")[$("button").index(event.target)]).show();
});
.hidden { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box hidden">box One</div>
<div class="box hidden">box Two</div>
<div class="box hidden">box Three</div>
<button type="button">One</button>
<button type="button">Two</button>
<button type="button">Three</button>

You can simply use the jQuery :not() selector.
$("#one").click(function () {
$(".box1").show();
$("div:not(.box1)").hide();
});
$("#two").click(function () {
$(".box2").show();
$("div:not(.box2)").hide();
});
$("#three").click(function () {
$(".box3").show();
$("div:not(.box3)").hide();
});

Related

How to get number of div left after deleting?

In my HTML there are eight div. I was able to get the number of the div using jQuery and insert it into the .num div element.
However when I delete one of the div by clicking the delete button, the number of divs in the span retrieved through jQuery won't update to the current number of divs remaining. It will still show 8.
How can I get the current number of div elements left in the DOM immediately after clicking the button?
setTimeout(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
The problem is because you're using setTimeout(), which only runs once after the specified delay.
For the pattern you're using to work you need to use setInterval() instead, which will run repeatedly at the set delay:
setInterval(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
However, using a timer for this is not ideal. As the number of div elements is only affected when the button is clicked, just update the .num span element in that event handler:
var $span = $(".num span").html($(".delete div").length);
$("button").click(function() {
$(".delete div:last-child").remove();
$span.html($(".delete div").length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>

How to hide the div with class name of button on click?

I need - button on click to hide each div, but here in my code only hide the first one then not working.
const closeInnermenu = document.querySelector('closeInnrmenu');
const innerC = document.querySelector('.inner-container')
closeInnermenu.addEventListener('click', () => {
innerC.style.display = 'none'
})
<div class="inner-container">
<div>Demo 1</div>
<button class="closeInnrmenu"></button>
</div>
<div class="inner-container">
<div>Demo 2</div>
<button class="closeInnrmenu"></button>
</div>
Get all the button using document.querySelectorAll('.closeInnrmenu') instead of document.querySelector since this will only give first matching element. Then iterate and add event listener to the button so that on click get the closest div and add style to it.
Also there is a type error here const closeInnermenu = document.querySelector('closeInnrmenu');. You need to pass dot as class selector
document.querySelectorAll('.closeInnrmenu').forEach((item) => {
item.addEventListener('click', function() {
this.closest('div').style.display = 'none'
})
})
<div class="inner-container">
<div>Demo 1</div>
<button class="closeInnrmenu">Close</button>
</div>
<div class="inner-container">
<div>Demo 2</div>
<button class="closeInnrmenu">Close</button>
</div>
Use:
let buttonClose = document.querySelectorAll('.closeInnrmenu')
for(let btns of buttonClose){
btns.addEventListener('click', function func(e) {
this.parentNode.style.display = 'none'
})
}
<div class="inner-container">
<div>Demo 1</div>
<button class="closeInnrmenu">Close</button>
</div>
<div class="inner-container">
<div>Demo 2</div>
<button class="closeInnrmenu">Close</button>
</div>
You can delegate
If you do not want to wrap in a div, use
document.addEventListener('click'
Here I wrapped
document.getElementById("container").addEventListener('click', (e) => {
const tgt = e.target;
if (tgt.classList.contains("closeInnrmenu")) {
tgt.previousElementSibling.style.display = 'none'
}
})
<div id="container">
<div class="inner-container">
<div>Demo 1</div>
<button class="closeInnrmenu"></button>
</div>
<div class="inner-container">
<div>Demo 2</div>
<button class="closeInnrmenu"></button>
</div>
</div>

How to correctly write jQuery toggle button that can work individualy?

I'm trying to create simple script which toggles buttons that can be placed anywhere on the page and work individualy no matter how the structure is.
$(document).ready(function() {
$('.togBtn').each(function(i) {
$(this).click(function() {
$('.togItem').hide();
} else {
$('.togItem').show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="togBtn" id="togBtn-1">
<button>But 1</button>
<div class="togItem" id="togItem-1">Item 1</div>
</div>
<button class="togBtn" id="togBtn-2">But 2</button>
<button class="togBtn" id="togBtn-3">But 3</button>
<div class="togItem" id="togBtn-2">Item 2</div>
<div class="togItem" id="togBtn-3">Item 3</div>
</section>
There's several issues in your code. Firstly a click handler function cannot have an else block. Secondly you try to hide/show all .togItem elements instead of the one related to the clicked button.
To approach this more logically, group the button and the content to be shown together. Then you can use DOM traversal to find the related item when the button is clicked. In the example below I made both of them children of a div and used next() to relate them. Try this:
jQuery(function($) {
$('.togBtn').click(function() {
$(this).next('.togItem').toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="togBtnContainer">
<button class="togBtn">But 1</button>
<div class="togItem">Item 1</div>
</div>
<div class="togBtnContainer">
<button class="togBtn">But 2</button>
<div class="togItem">Item 2</div>
</div>
<div class="togBtnContainer">
<button class="togBtn">But 3</button>
<div class="togItem">Item 3</div>
</div>
</section>
If the HTML is spread out and the related elements are not siblings then you can instead use data attributes to relate them, like this:
jQuery(function($) {
$('.togBtn').click(function() {
var targetSelector = $(this).data('target');
$(targetSelector).toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="togBtn" id="togBtn-1" data-target="#togItem-1">
<button>But 1</button>
<div class="togItem" id="togItem-1">Item 1</div>
</div>
<button class="togBtn" id="togBtn-2" data-target="#togItem-2">But 2</button>
<button class="togBtn" id="togBtn-3" data-target="#togItem-3">But 3</button>
<div class="togItem" id="togItem-2">Item 2</div>
<div class="togItem" id="togItem-3">Item 3</div>
</section>
Get the id of the button (or its parent element if the button itself doesn't have one) with the help of .closest() and the "attribute starts with" selector (^=):
var togBtnId = $(this).closest('[id^="togBtn-"]').attr("id");
Then just replace togBtn with togItem to get the id of the related item and use this as the selector for .toggle():
$("#" + togBtnId.replace("togBtn", "togItem")).toggle();
Example:
$(".togBtn").on("click", function() {
var togBtnId = $(this)
.closest('[id^="togBtn-"]') // .closest() because "But 1" has no id itself but its parent
.attr("id");
if (togBtnId) {
$("#" + togBtnId.replace("togBtn", "togItem")).toggle();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="togBtn" id="togBtn-1">
<button>But 1</button>
<div class="togItem" id="togItem-1">Item 1</div>
</div>
<button class="togBtn" id="togBtn-2">But 2</button>
<button class="togBtn" id="togBtn-3">But 3</button>
<div class="togItem" id="togItem-2">Item 2</div>
<div class="togItem" id="togItem-3">Item 3</div>
</section>

Edit css of "item" when clicking on corresponding "btn"

So I have this
<div class="btns">
<div class="btn1"></div>
<div class="btn2"></div>
<div class="btn3"></div>
<div class="btn4"></div>
</div>
<div class="prevs">
<div class="pre1"></div>
<div class="pre2"></div>
<div class="pre3"></div>
<div class="pre4"></div>
</div>
http://jsfiddle.net/uzpxjukv/
You have btn1, btn2, btn3 and btn4. I'm trying to make it so that when you press btn1, the div with the class pre1 should then get "display: block;" or something to make it visible. Then when btn2 is clicked, pre1 turns invisible again and pre2 turns visible.
Maybe something like this? If there will be more buttons, it should be more optimalized.
$('.btns').find('div').click(function(){
$('.prevs').find('div').eq($(this).index()).toggle();
});
$('.btns').find('div').click(function(){
$('.prevs').find('div').eq($(this).index()).toggle();
});
.prevs div:not(.pre1) {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btns">
<div class="btn1">Button 1</div>
<div class="btn2">Button 2</div>
<div class="btn3">Button 3</div>
<div class="btn4">Button 4</div>
</div>
<div class="prevs">
<div class="pre1">Previews 1</div>
<div class="pre2">Previews 2</div>
<div class="pre3">Previews 3</div>
<div class="pre4">Previews 4</div>
</div>
JSFIDDLE DEMO -> http://jsfiddle.net/uzpxjukv/5/
$('.btns div').click(function() {
var classNumber = this.className.slice(-1);
$('.prevs div').hide();
$('.pre' + classNumber).show();
});
On click of the button div, first hide all the pre divs and then show only the relevant div.
Try it
$('.btns > div').on('click', function() {
var numberOfDiv = $(this).attr('class').slice('-1'),
prevs = $('.prevs');
prevs.find('> div').hide();
prevs.find('.pre' + numberOfDiv).show();
});
This example is with your html code, if is possible to change it, you can get a better code.
See the fiddle
I have changed your HTML a little bit..Changed the class attribute of the prevs divsti ids.
HTML
<div class="btns">
<div class="btn1" id="1" onClick="reply_click(this.id)"></div>
<div class="btn2" id="2" onClick="reply_click(this.id)"></div>
<div class="btn3" id="3" onClick="reply_click(this.id)"></div>
<div class="btn4" id="4" onClick="reply_click(this.id)"></div>
</div>
<div class="prevs">
<div id="pre1"></div>
<div id="pre2"></div>
<div id="pre3"></div>
<div id="pre4"></div>
</div>
JS
function reply_click(id) {
document.getElementById("pre" + id).style.display = "block";
}
Provided that you know what naming system the divs use, you could use something along these lines. (To see properly working, view using developer tool)
$('.btns div').on('click', function() {
var currClass = $(this).attr('class').slice(-1); //get end of number of div clicked
$('.prevs div').css('display', 'none'); //reset all divs to being hidden
$('.pre' + currClass).css('display', 'inline-block'); //show desired div
});
.btns div {
background-color: gray;
}
.btns div, .prevs div {
width: 2em;
height: 2em;
display: inline-block;
padding-right: 0.2em;
}
.prevs div {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btns">
<div class="btn1"></div>
<div class="btn2"></div>
<div class="btn3"></div>
<div class="btn4"></div>
</div>
<div class="prevs">
<div class="pre1"></div>
<div class="pre2"></div>
<div class="pre3"></div>
<div class="pre4"></div>
</div>

javascript loop needed to show hidden list onclick one at a time

I have a list of hidden divs and would like to be able to show one div at a time, when a button is pressed, .. I am having a hard time writing the proper loop for this.
product_options: function() {
var product_option = $('.product_product_options_option_name')
$(product_option).css("display", "none");
$('.add_product_option').on('click', function (e) {
e.preventDefault();
$(product_option).each(function(){
$(this).css("display", "block")
});
});
}
currently it displays them all onclick, i deleted all my other loop attempts, bc they were egregiously wrong or were not doing much
Try
product_option.first().show(); //show only the first one
product_option = product_option.slice(1); //remove the first one
Demo:
$(function() {
var options = $('.product_option').hide();
$('.add').click(function() {
if(options.length) {
options.first().show();
options = options.slice(1);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="product_option">Option 1</div>
<div class="product_option">Option 2</div>
<div class="product_option">Option 3</div>
<div class="product_option">Option 4</div>
<div class="product_option">Option 5</div>
<div class="product_option">Option 6</div>
<div class="add">Add product option</div>
product_options: function() {
var product_option = $('.product_product_options_option_name')
$(product_option).css("display", "none");
$('.add_product_option').on('click', function (e) {
e.preventDefault();
$(product_option + ':hidden').eq(0).show();
});
}
try this : demo
$('.product_product_options_option_name').hide();
var count = 0;
$('.add_product_option').on('click',function(){
$('.product_product_options_option_name:eq('+count+')').show();
count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="add">
<input type="button" class="add_product_option" value="click" />
</div>
<div class="product_product_options_option_name">
<label>1div</label>
</div>
<div class="product_product_options_option_name">
<label>2div</label>
</div>
<div class="product_product_options_option_name">
<label>3div</label>
</div>
<div class="product_product_options_option_name">
<label>4div</label>
</div>

Categories

Resources