How to concatenate values in one variable - javascript

How can I concatenate the values of my div when they are click in one variable?
here is my code sample.
var concatenated_values; //1,2,3
$("#first_container").click(function() {
console.log($("#first_container input:hidden").val());
});
$("#second_container").click(function() {
console.log($("#second_container input:hidden").val());
});
$("#third_container").click(function() {
console.log($("#third_container input:hidden").val());
});
#first_container, #second_container , #third_container{
width:300px;
height:200px;
background:red;
cursor:pointer;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div id="first_container">
<p>Test 1</p>
<input type="hidden" value='1'/>
</div>
<div id="second_container">
<p>Test 2</p>
<input type="hidden" value='2'/>
</div>
<div id="third_container">
<p>Test 3</p>
<input type="hidden" value='3'/>
</div>
</div>
</body>
</html>
so when I click all of my div I am trying to have a value in my concatenated_values like this
1,2,3
and I still can click the other div it is like unselecting, so when I click the selected div, it should update my variable and remove its value on it.
1,3
Any help would be really appreciated.

Make your variable as a array and save the values of the divs in that array.
Afterwards you can loop through that array and print all values if needed or make use of other array functions like reduce to calculate i.e. the sum.
var concatenated_values = []; //1,2,3
$("#first_container").click(function() {
const input = $("#first_container input:hidden").val();
if (concatenated_values.includes(input))
concatenated_values.splice(concatenated_values.indexOf(input), 1);
else
concatenated_values.push($("#first_container input:hidden").val());
console.log(concatenated_values);
});
$("#second_container").click(function() {
const input = $("#second_container input:hidden").val();
if (concatenated_values.includes(input))
concatenated_values.splice(concatenated_values.indexOf(input), 1);
else
concatenated_values.push($("#second_container input:hidden").val());
console.log(concatenated_values);
});
$("#third_container").click(function() {
const input = $("#third_container input:hidden").val();
if (concatenated_values.includes(input))
concatenated_values.splice(concatenated_values.indexOf(input), 1);
else
concatenated_values.push($("#third_container input:hidden").val());
console.log(concatenated_values);
});
#first_container,
#second_container,
#third_container {
width: 300px;
height: 200px;
background: red;
cursor: pointer;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div id="first_container">
<p>Test 1</p>
<input type="hidden" value='1' />
</div>
<div id="second_container">
<p>Test 2</p>
<input type="hidden" value='2' />
</div>
<div id="third_container">
<p>Test 3</p>
<input type="hidden" value='3' />
</div>
</div>
</body>
</html>

You can store the values in an array and then push or filter the value if is present/not present in the array.
var concatenated_values = []; //1,2,3
$("#first_container").click(function() {
checkValues($("#first_container input:hidden").val());
console.log(concatenated_values.join(','));
});
$("#second_container").click(function() {
checkValues($("#second_container input:hidden").val());
console.log(concatenated_values.join(','));
});
$("#third_container").click(function() {
checkValues($("#third_container input:hidden").val());
console.log(concatenated_values.join(','));
});
function checkValues(x) {
var i = concatenated_values.indexOf(x);
if(i !== -1) {
concatenated_values = concatenated_values.filter(function(v){
return v !== x;
});
} else {
concatenated_values.push(x);
}
}
#first_container, #second_container , #third_container{
width:300px;
height:200px;
background:red;
cursor:pointer;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div id="first_container">
<p>Test 1</p>
<input type="hidden" value='1'/>
</div>
<div id="second_container">
<p>Test 2</p>
<input type="hidden" value='2'/>
</div>
<div id="third_container">
<p>Test 3</p>
<input type="hidden" value='3'/>
</div>
</div>
</body>
</html>

You really don't need to add the separate click event for each of the div.
Then give some border or change the background color to know the difference clicked or not. So I have added some class if it is clicked.
So the final code is
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
var concatenated_values = [];
$().ready(function () {
$("#first_container, #second_container, #third_container").click(function () {
var val = $(this).find('input:hidden').val();
var indx = concatenated_values.indexOf(val);
if (indx > -1) {
concatenated_values.splice(indx, 1);
$(this).removeClass('selected');
} else {
concatenated_values.push(val);
$(this).addClass('selected');
}
console.log(concatenated_values);
});
});
</script>
<style>
#first_container,
#second_container,
#third_container {
width: 300px;
height: 200px;
background: red;
cursor: pointer;
margin:10px;
padding: 10px;
}
.selected {
border: 2px solid rgb(48, 47, 46);
}
</style>
</head>

I would suggest you change your logic to not use a global variable at all. If you amend the HTML so that you place a common class on each clickable div, then you can use a class to keep track of which is 'active', in order to make an array of the child input values. You can then join() this to make the string you require.
This approach is more maintainable, extensible and simpler. Here's an example:
$('.sub-container').on('click', e => {
let $this = $(e.target).toggleClass('active');
let concatenated_values = $('.active').map((i, el) => $(el).find('input').val()).get().join(',');
console.log(concatenated_values);
});
.sub-container {
width: 300px;
height: 200px;
background: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div id="first_container" class="sub-container">
<p>Test 1</p>
<input type="hidden" value="1" />
</div>
<div id="second_container" class="sub-container">
<p>Test 2</p>
<input type="hidden" value="2" />
</div>
<div id="third_container" class="sub-container">
<p>Test 3</p>
<input type="hidden" value="3" />
</div>
</div>

Using classes will simplify things, below I use a class called selected, you can then use the toggleClass method to flip on an off.
You can then just find all Div's with the selected class, and add up the values.
eg.
$('.container > div').click(function () {
var $t = $(this);
$t.toggleClass('selected');
var concatenated = [];
$t.closest('.container')
.find('.selected').each(function () {
concatenated.push($(this).find('input').val());
});
$('#result').text(concatenated.join(','));
});
.container > div {
width:300px;
height:30px;
background:red;
cursor:pointer;
}
.container > .selected {
background: pink;
}
#result {
width:300px;
height:30px;
background: yellow;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div id="first_container">
<p>Test 1</p>
<input type="hidden" value='1'/>
</div>
<div id="second_container">
<p>Test 2</p>
<input type="hidden" value='2'/>
</div>
<div id="third_container">
<p>Test 3</p>
<input type="hidden" value='3'/>
</div>
</div>
<p>Result</p>
<div id="result"></div>
</body>
</html>

Related

Random Image for 404

To start off I'm terrible at Js and super new at it. I'm trying to make a random image pop up when the site goes to a 404. I can't tell if my website is actually running the code or not because console.log wasn't working. Because of that I took all my CSS and js and put it all into the same HTML file to see if that was the problem (it wasn't) Any help is much appreciated :)
HTML:
<html>
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<div id="getMeme()"></div>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
document.getElementById("result").onload = '<img src="' + meme[pp] + '" />';
}
</script>
</html>
Using your code, you would need to ensure the function getMeme is called/invoked. Furthermore, you would need to update the function to modify the innerHTML of the element with id result instead of assigning to it's event handler onload.
See demo below:
I've included a console.log for debugging purposes on stackoverflow as images shared in the question are not available.
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<span id="result"></span>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
console.log("chose meme",meme[pp]); //line included for debugging purposes on stackoverflow as images shared in question are not available
//update `innerHTML` of target element
document.getElementById("result").innerHTML = '<img src="' + meme[pp] + '" />';
}
//call function to getMeme at the end of the page
getMeme();
</script>
</body>
</html>

In html how to pass div class content (text) to another class or id?

For example, i have <div id="titlebar"></div> inside html, and also i have <div class="name">Content-text</div> inside same html. Now i want pass Content-text of div class name (<div class="name">Content-text</div>) to another my id <div id="titlebar"></div> through css or js. i tried several ways, but no effect
And when i scroll up the html the id titlebar will show the text of class name
My html:
<html>
<body>
<div id="titlebar"></div>
<div class="name">Content-text</div>
</body>
</html>
Css:
#titlebar{
text-align:center;
width: 101%;
position: fixed;
top:0px;
margin-left:-10px;
padding-right:1px;
font-family: Times New Roman;
font-size: 16pt;
font-weight: normal;
color: white;
display:none;
border: none;
}
Javascript:
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {
document.getElementById("titlebar").style.display = "block";
} else {
document.getElementById("titlebar").style.display = "none";
}
}
Working Sample, jsFiddle
Please find it here.
<style>
#titlebar{
border: 1px solid black;
}
.name{
border: 1px solid red;
}
</style>
<div>
<div id="titlebar"></div>
<br/>
<div class="name">Content-text</div>
<button id='btn'>
Click to cpoy and put text inside titlebar
</button>
</div>
<script>
document.getElementById('btn').addEventListener('click', function() {
// Find your required code hre
let textInsideDivelementWithclass = document.getElementsByClassName('name')[0].innerText,
titlebarEle = document.getElementById('titlebar');
titlebarEle.innerText = textInsideDivelementWithclass;
});
</script>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var Content_text = $(".name").text();
$("#titlebar").text(Content_text);
});
});
</script>
</head>
<body>
<button>Copy</button>
<div class="name">Content-text</div>
<div id="titlebar">copy here</div>
</body>
</html>
First you get the text of your .name element:
let nameElement = document.querySelector(".name").textContent;
then you get the target element and assign the .name text to it :
document.querySelector("#titlebar").textContent = nameElement;
First of all you should determin an id for your div like this:
<div id="name">Content-text</div>
then use this code:
<script type="text/javascript">
var DivName = document.getElementById('name');
var DivTitlebar = document.getElementById('titlebar');
DivTitlebar.innerHTML = DivName.innerHTML;
</script>
Please try this..
You have to get the content from the div1 and div2 to two seperate variables div1Data and div2Data
Then from the HTML DOM innerHTML Property you can assign the content to your preferred div
function copyContent() {
var div1Data= document.getElementById('div1');
var div2Data= document.getElementById('div2');
div2Data.innerHTML = div1Data.innerHTML;
}
<div id="div1">
Content in div 1
</div>
<div id="div2">
</div>
<button onClick="copyContent()">Click to copy</button>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<script>
$(document).ready(function(){
var Content_text = $(".name").text();
//alert(Content_text);
$(function() {
$(window).mousewheel(function(turn, scroll) {
if (scroll > 0) $('#titlebar').text('Content_text');
else $('#titlebar').text('Copy here');
return false;
});
});
//$("#titlebar").text(Content_text);
});
</script>
</head>
<body>
<div class="name" style="margin-top:50px;">Content-text</div>
<div id="titlebar" style="margin-top:50px;">Copy here</div>
</body>
</html>

jQuery closest() appears to find parent id when there is none

I have an event listener for when the user clicks in the window. I want to see if the clicked element has any parent element with a certain id. I use the jQuery closest() function for that. But it always returns true.
Here is a fiddle that demonstrates my code.
There must be some major error, because if I change the id from if($(event.target).closest('#activatemenu'))
into any other id
if($(event.target).closest('#rrrrrrr'))
it still returns true.
Code in fiddle:
$(function() {
$(document).click(function(event) {
if($(event.target).closest('#activatemenu')) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activatemenu</p>');
}else{
$('.wrap p').remove();
}
});
});
.stuff{
width:300px;
height:150px;
border:red 2px solid;
}
.otherstuff{
width:400px;
height:400px;
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activatemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
Closest always returns a jQuery object which resolves to truthy. You need to check the length of the object.
$(event.target).closest('#rrrrrrr').length
Or, use
$(function() {
$(document).click(function(event) {
if ($(event.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
} else {
$('.wrap p').remove();
}
});
});
.stuff {
width: 300px;
height: 150px;
border: red 2px solid;
}
.otherstuff {
width: 400px;
height: 400px;
background: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
$(event.target).closest('#activatemenu') will always return an object so if condition will always be true, better check for $(event.target).closest('#activatemenu').length
$(function() {
$(document).click(function(event) {
if($(event.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
}else{
$('.wrap p').remove();
}
});
});
.stuff{
width:300px;
height:150px;
border:red 2px solid;
}
.otherstuff{
width:400px;
height:400px;
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>
You have two problems with your code.
First, you need to search for the closest activemenu not activatemenu. activatemenu does not exist in your code.
Second, jQuery will always return an array so you need to check the length to see whether the element was found as a non-empty array will always return true.
See below for a working example:
$(function() {
$(document).click(function(evt) {
if($(evt.target).closest('#activemenu').length) {
$('.wrap').prepend('<p>the clicked element has a parent with the id of activemenu</p>');
} else {
$('.wrap p').remove();
}
});
});
.stuff {
width: 300px;
height: 150px;
border: red 2px solid;
}
.otherstuff {
width: 400px;
height: 400px;
background: purple;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<div class="wrap">
<div id="activemenu">
<div>
<div>
<div class="stuff">
<p>Here is some text</p>
</div>
</div>
</div>
</div>
<div class="otherstuff">
<p>Other stuff!</p>
</div>
</div>

how to perform div hover shows another div but both div's are different form?

i have created two forms, one form having the div that div id is "one" second form having the another div id is "two".When div one hover the div two wants to be displayed. i have tried like this.
<form action="">
<div id="one">
<p>source of hover content</p>
</div>
</form>
<form action="">
<div id="two">
<p>destination of hover content</p>
</div>
</form>
In Css:
#two{
display: none;
}
#one:hover #two {
display: block;
}
To show/hide second div on hover of first div use below script.
$(function(){
$("#one,#two").hover(function(){
$("#two").show();
},function(){
$("#two").hide();
});
});
Please check working demo:
$(function(){
$("#one,#two").hover(function(){
$("#two").show();
},function(){
$("#two").hide();
});
});
#two{
display: none;
}
#one:hover #two {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<div id="one">
<p>source of hover content</p>
</div>
</form>
<form action="">
<div id="two">
<p>destination of hover content</p>
</div>
</form>
var clr;
$(document).ready(function()
{
$(function() {
$("#one,#two").bind('mouseout', function(){
clr = setTimeout( function(){$("#two").css("display", "none");} , 2000);
})
});
$(function() {
$("#one,#two").bind('mouseover', function(){
clearTimeout(clr);
$("#two").css("display", "block");
})
});
});
var clr;
$(document).ready(function()
{
$(function() {
$("#one,#two").bind('mouseout', function(){
clr = setTimeout( function(){$("#two").css("display", "none");} , 500);
})
});
$(function() {
$("#one,#two").bind('mouseover', function(){
clearTimeout(clr);
$("#two").css("display", "block");
})
});
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<form action="">
<div id="one" style="border: 1px solid #000; width:200px;padding:5px;">
<p>source of hover content</p>
</div>
</form>
<form action="">
<div id="two" style="border: 1px solid #000; width:200px;padding:5px;display:none;">
<p>destination of hover content</p>
</div>
</form>
Give an ID to each of your forms
Then, you can use jQuery to point a specific element within a form
<form id="form1" action="">
<div id="one">
<p>source of hover content</p>
</div>
</form>
<form id="form2" action="">
<div id="two">
<p>destination of hover content</p>
</div>
</form>
Using jQuery you can specify each element inside a particular form
$(document).ready(function() {
$("#form2 #two").hide();
$("#form1 #one").hover(function(){
$("#form2 #two").show();
});
});
Pure JavaScript and supported in all browsers using Element.style.display and Element.onmouseover & Element.onmouseout for hover events
String.prototype.Tshow = function(s){
document.getElementById(this).style.display = s ? "block" : "none";
}
document.getElementById("one").onmouseover = function(){"two".Tshow(true)}
//to hide onmouseout
/*
document.getElementById("one").onmouseout = function(){"two".Tshow(false)}
*/
#two{
display: none;
}
#one:hover{
display: block;
}
<form action="">
<div id="one">
<p>source of hover content</p>
</div>
</form>
<form action="">
<div id="two">
<p>destination of hover content</p>
</div>
</form>

Hide Previous div and toggle next div on click a button?

I have a number of buttons in my html. Each button referring to a particular DIV. I want an easy way to hide the previously open DIV when another button is clicked. So far I have written a code in jquery, but I have a strange feeling that am putting in a lot of code into a simply achievable task. Is there a simpler way to do this than what I have tried to accomplish?
Here is what I have done so far.
My HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width"/>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<div id="body">
<input type="button" name="division1" value="div1" class="buttons" id="button1"/>
<input type="button" name="division2" value="div2" class="buttons" id="button2"/>
<input type="button" name="division3" value="div3" class="buttons" id="button3"/>
<input type="button" name="division4" value="div4" class="buttons" id="button4"/>
<input type="button" name="division5" value="div5" class="buttons" id="button5"/>
<input type="button" name="division6" value="div6" class="buttons" id="button6"/>
<div id="div1" class="divs"></div>
<div id="div2" class="divs"></div>
<div id="div3" class="divs"></div>
<div id="div4" class="divs"></div>
<div id="div5" class="divs"></div>
<div id="div6" class="divs"></div>
</div>
</body>
</html>
My CSS:
#body{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: #000;
}
.buttons{
width: 10%;
height: 5%;
position: relative;
left: 10%;
cursor: pointer;
z-index: 500;
}
.divs{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: none;
}
#div1{
background-color: #377D9F;
}
#div2{
background-color: #02B0E6;
}
#div3{
background-color: #4b9500;
}
#div4{
background-color: #aaa;
}
#div5{
background-color:#aa0000;
}
#div6{
background-color: aquamarine;
}
My Jquery:
$(document).ready(function () {
$("#button1").click(function () {
$('#div1').toggle(100);
$("#div2,#div3,#div4,#div5,#div6").hide();
});
$("#button2").click(function () {
$("#div2").toggle(100);
$("#div1,#div3,#div4,#div5,#div6").hide();
});
$("#button3").click(function () {
$("#div3").toggle(100);
$("#div1,#div2,#div4,#div5,#div6").hide();
});
$("#button4").click(function () {
$("#div4").toggle(100);
$("#div1,#div2,#div3,#div5,#div6").hide();
});
$("#button5").click(function () {
$("#div5").toggle(100);
$("#div1,#div2,#div3,#div4,#div6").hide();
});
$("#button6").click(function () {
$("#div6").toggle(100);
$("#div1,#div2,#div3,#div4,#div5").hide();
});
});
I kind of have around 50 DIV's in my html like the above ones. And I think using the above JQUERY is a waste of coding lines. I know there will be a better way to do this. My code seems to work well, but is there any way in jquery to just hide the previous DIV, no matter which button user clicks?
$(document).ready(function(){
$(".buttons").click(function () {
var divname= this.value;
$("#"+divname).slideToggle().siblings('.divs').hide("slow");
});
});
Going with this sentence I kind of have around 50 DIV's in my html like the above ones
This would be a lot more clean as well as convenient if you use a select tag, instead of using button to show and hide each div
Demo
HTML
<select id="show_divs">
<option>Select to show a div</option>
<option value="1">Show 1</option>
<option value="2">Show 1</option>
</select>
<div class="parent">
<div id="show1">This is the first div</div>
<div id="show2">This is the second div</div>
</div>
jQuery
$('#show_divs').change(function() { //onChange execute the function
var showDiv = $(this).val(); //Store the value in the variable
$('div.parent > div').hide(); //Hide all the div nested inside .parent
$('#show' + showDiv ).show(); //Fetch the value of option tag, concatenate it with the id and show the relevant div
});
CSS
div.parent > div {
display: none; /* Hide initially */
}
If you want to avoid using id's, you can also create your custom attribute, like data-show="1" and data-show="2" so on...
Try this
$(document).ready(function() {
$(".divs").hide();
$(".buttons").click(function() {
$(".divs").hide().eq($(this).index()).show();
});
});
DEMO
<input type="button" value="div1" class="buttons" id="button1" />
<input type="button" value="div2" class="buttons" id="button2" />
<input type="button" value="div3" class="buttons" id="button3" />
<input type="button" value="div4" class="buttons" id="button4" />
<input type="button" value="div5" class="buttons" id="button5" />
<input type="button" value="div6" class="buttons" id="button6" />
<div id="div1" class="divs">div1</div>
<div id="div2" class="divs">div2</div>
<div id="div3" class="divs">div3</div>
<div id="div4" class="divs">div4</div>
<div id="div5" class="divs">div5</div>
<div id="div6" class="divs">div6</div>
<script language="javascript">
$(document).ready(function () {
$(".buttons").click(function () {
$('.divs').hide();
$('#div'+$(this).attr('id').replace('button','')).toggle(100);
})
})
</script>

Categories