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

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>

Related

jQuery ready function for multiple drawings

I am trying to use jQuery ready function for multiple ids so that they show and hide individually without writing the same type again and again. When I try to use it on the same line it opens all the drawings all together. The code looks something like this-
<script type="text/javascript">
$(document).ready(function(){
$('#p1','#p2', '#p3','#p4').hide();
$('#p1-show','#p2-show','#p3-show','#p4-show').click(function(){
$('#p1','#p2','#p3','#p4').show();
});
$('#p1-hide','#p2-hide','#p3-hide','#p4-hide').click(function(){
$('#p1','#p2','#p3','#p4').hide();
});
});
</script>
Your function hides all of them. If you want to hide the drawing based on which show/hide button is clicked, you can use $(this) to find the corresponding drawing.
The exact code will depend on how your elements are structured, but the idea is to use $(this) to target the element that was clicked, and from there find the element you want to hide.
Here's an example:
$(document).ready(function(){
$('#p1, #p2, #p3, #p4').hide();
$('#p1-show, #p2-show, #p3-show, #p4-show').click(function(){
$(this).parent().find('p').show();
});
$('#p1-hide, #p2-hide, #p3-hide, #p4-hide').click(function(){
$(this).parent().find('p').hide();
});
});
div {
margin: 10px;
padding: 10px;
background-color: #eee;
border-radius: 10px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="p1">First Drawing</p>
<button id="p1-show">Show</button>
<button id="p1-hide">Hide</button>
</div>
<div>
<p id="p2">Second Drawing</p>
<button id="p2-show">Show</button>
<button id="p2-hide">Hide</button>
</div>
<div>
<p id="p3">Third Drawing</p>
<button id="p3-show">Show</button>
<button id="p3-hide">Hide</button>
</div>
<div>
<p id="p4">Fourth Drawing</p>
<button id="p4-show">Show</button>
<button id="p4-hide">Hide</button>
</div>
The previous answers will work, but in case there are many such drawings then giving an #id to all those becomes badly repetitive and should be avoided. Following is a code snippet to make it more robust without much hard coded #ids.
$(function(){
$('.toggle-btn').on('click', function(){
var root = $(this).closest(".picture-container");
var img = $(root).find("img");
$(img).toggle();
});
});
body > div {
margin: 10px;
padding: 10px;
background-color: #eee;
border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="picture-container">
<button class="toggle-btn">Show/Hide</button>
<div>
<img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
</div>
</div>
<div class="picture-container">
<button class="toggle-btn">Show/Hide</button>
<div>
<img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
</div>
</div>
<div class="picture-container">
<button class="toggle-btn">Show/Hide</button>
<div>
<img src="http://24.media.tumblr.com/tumblr_lggvvf2mCm1qgnva2o1_500.gif">
</div>
</div>
You really don't need all of these selectors you have. It's overkill.
You should have your markup all the same for each 'drawing' it makes replication of this 'module' much easier for you also.
$(document).ready(function(){
//this hides all of your <p> on page load
$('p').hide();
//this adds the click event to all the buttons with 'show'
$('.show').on('click', function(){
$(this).parent().find('p').show();
});
$('.hide').on('click', function(){
$(this).parent().find('p').hide();
})
});
div {
margin: 10px;
padding: 10px;
background-color: #eee;
border-radius: 10px;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>1st Image</p>
<button class="show">show</button>
<button class="hide">hide</button>
</div>
<div>
<p>2nd Image</p>
<button class="show">show</button>
<button class="hide">hide</button>
</div>
<div>
<p>3rd Image</p>
<button class="show">show</button>
<button class="hide">hide</button>
</div>
<div>
<p>4th Image</p>
<button class="show">show</button>
<button class="hide">hide</button>
</div>
<div>
<p>5th Image</p>
<button class="show">show</button>
<button class="hide">hide</button>
</div>

Changing the function of a button in a website

So below I have some code of what I'm working with. Right now, if you just launch the website, the #picture div has a background image, and if you press any of the buttons, that picture is replaced with something else.
So what I can't figure out is how the buttons would change what they do after pressing a button. Let's say you click on Button 1 and the background image is replaced. I want the buttons to recognize what background image is in that div and change functions accordingly, in my case, I want them to change what pictures they replace the current one with.
If the current background of #picture is X, you have ABC choices, if the background of #picture is Y, you have DEF choices, would be a TLDR explanation maybe.
<div id="adventure">
<div class="picture">
</div>
<div id="choice">
<button class="button1">Val 1</button>
<button class="button2">Val 2</button>
<button class="button3">Val 3</button>
</div>
</div>
$('.button1').click(function() {
$('.picture').css('background-image',
'url("image1")'
);
});
$('.button2').click(function() {
$('.picture').css('background-image',
'url("image2")'
);
});
$('.button3').click(function() {
$('.picture').css('background-image',
'url("image3")'
);
});
I've probably gone about doing this in a bad way but I'm really at a loss on how I would do this. I can only think up of one way of doing it and that is to have a bunch of if statements depending on what background is in the #picture div but I don't know how to implement that.
This demo relies on the class .active which determines which set of buttons (called .group) are visible, whilst the other .groups remain absent. The #switch button will toggle through each group.
You must name your images according to the id of the button it belongs to.
Example:
HTML of Button
<button id="image_of_sky.png">D</button>
URL to Image
http://domain.com/path/to/image_of_sky.png
jQuery img variable
var img = "http://domain.com/path/to/"+btn;
Snippet
$('.button').click(function() {
var btn = $(this).attr('id');
var img = "https://placehold.it/330x150?text=" + btn;
$('.picture').css('background-image',
'url(' + img + ')'
);
});
$('#switch').click(function() {
var act = $('.group.active');
var next = act.next();
act.removeClass('active');
next.addClass('active');
if (act.attr('id') == "choiceGHI") {
$('#choiceABC').addClass('active');
}
});
#adventure {
width: 395px;
}
.picture {
width: 330px;
height: 150px;
border: 1px outset grey;
}
.group {
width: 330px;
display: none;
padding: 0;
}
.button {
width: 32.5%;
margin: 0;
}
.active {
display: block;
}
#switch {
float: right;
margin: -20px 0 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="adventure">
<div class="picture"></div>
<div id="choiceABC" class="group active">
<button id="Image1" class="button">A</button>
<button id="Image2" class="button">B</button>
<button id="Image3" class="button">C</button>
</div>
<div id="choiceDEF" class="group">
<button id="Image4" class="button">D</button>
<button id="Image5" class="button">E</button>
<button id="Image6" class="button">F</button>
</div>
<div id="choiceGHI" class="group">
<button id="Image7" class="button">G</button>
<button id="Image8" class="button">H</button>
<button id="Image9" class="button">I</button>
</div>
<button id="switch">Switch</button>
</div>

How to hide div when it's already open?

I couldn't think of any better title, so I will try to explain my question here as clear as possible. I'm quite a newbie in JQuery so this is probably a very easy question.
I have some divs with a button on it. When you click the button, another div should pop-up.
My question is: How can I make the div, which is already open, close when clicking on another button?
I made a fiddle with some example code: http://jsfiddle.net/zuvjx775/1/
And the example code here:
HTML:
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2"value='click!' />
</div>
<div class="show_2">
</div>
</div>
JQuery:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
$('.show_'+id).show();
});
When show_1 for example is visible, and I click on the button in div2, I want show_2 to come up, which it does, but show_1 to dissapear.
Can someone point me in the right direction?
You can hide all divs that their class starts with 'show' before show the one you want. For example:
$('.showDiv').on('click', function() {
var id = $(this).attr('id');
$("div[class^='show']").hide();//find div class starts with 'show' and hide them
$('.show_' + id).show();
});
.test {
border: 1px solid black;
height: 100px;
width: 450px;
float: left;
}
.show_1 {
width: 50px;
height: 50px;
background-color: yellow;
float: left;
display: none;
}
.show_2 {
width: 50px;
height: 50px;
background-color: green;
float: left;
display: none;
}
.wrapper {
clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="1" value='click!' />
</div>
<div class="show_1">
</div>
</div>
<br>
<div class="wrapper">
<div class="test">
<input type='button' class='showDiv' id="2" value='click!' />
</div>
<div class="show_2">
</div>
</div>
Is the structure of the document fixed?
is so... I guess the easiest way of doing this is to just do the following:
$('.showDiv').on('click', function(){
var id = $(this).attr('id');
if(id == 1){
$('.show_1').show();
$('.show_2').hide();
}else{
$('.show_2').show();
$('.show_1').hide();
}
})

Hide multiple <div> on page loaded by ajax call till button click

I have already seen similar threads on SO.
I have index.php on button click url.php get loaded through ajax in the <div> present in index.php
On url.php there are couple of <div>. I want some of them to be visible only after button click. I got solution for this.
But only 1 div become visible rest hidded Is it due to z-index property?
index.php:
<script>
$("#load_url").click(function(){
$.ajax({
url:"url.php",
success:function(response) {
$("#view_port").html(response);
$("#load_url").hide();
}
});
});
function show2() {
//alert("hi");
document.getElementById("txtHint").style.display = "block";
document.getElementById("rateit99").style.display = "block";
document.getElementById("cb1").style.display = "block";
}
</script>
url.php
<body style="height: 560px">
<div class="rateit bigstars" id="rateit99" style="z-index: 1; display:none;" ><b>Rate Me </b></label>
</div>
<label2 color="red" id="l1" style="z-index: 1; left: 438px; display:none; top: 180px; position:absolute" ><b><u>Add comment</u> </b></label2>
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
<div style="z-index: 1; left: 420px; top: 40px; position: absolute; margin-top: 0px">
<label>Enter URL: <input type="text" id="t1" value="http://www.paulgraham.com/herd.html" name="sent" style="width: 400px; height:40px;" ></label><br/>
</div>
<div style="z-index: 1;" > <button onclick="show2();"> Get Sentiment </button>
</div>
</form>
<div style="z-index: 1; left: 720px; top: 110px; position: absolute; margin-top: 0px">
</div>
<h4>
<div id="txtHint" align="justify" style="z-index: 3; "> </h4>
</div>
<div class="fb-comments" id='cb1'" ></div>
</div>
</body>
when button Get Sentiment clicked. Only id="txtHint" and lable Rate me appears.
cb1, rateit99 remains invisible, what is the bug here?
Link to full code:
index.php
http://codetidy.com/6857/
url.php
http://codetidy.com/6858/
Its not a answer but because I can not comment-
Actually this is happening because of css conflicts. try to give display none every such element through class and then apply direct style as ur doing. you can also use !important to give higher preference.

jQuery - Simple Image Rotator

On fiddle I found a simple rotator and trying to make it work in my death-simple HTML page.
The page example is here:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
img { max-height: 100px }
.rotator img { max-height: 200px; border: dashed 5px pink; }​
</style>
<script>
$(document).ready(function() {
alert('aaa');
var $rotator = $(".rotator");
$rotator.find("img:gt(0)").hide();
setTimeout(Rotate, 1000);
function Rotate() {
var $current = $rotator.find("img:visible");
var $next = $current.next();
if ($next.length == 0) $next = $rotator.find("img:eq(0)");
$current.hide();
$next.show();
setTimeout(Rotate, 5000);
}​
});
</script>
</head>
<body>
<img src="http://2.bp.blogspot.com/-XI9yzJrwLac/TkLKLZF_kDI/AAAAAAAACFE/PxPDRzwa4tQ/s1600/cute+cats+pictures+3.jpg"/>
<img src="http://2.bp.blogspot.com/-NOD8B0m7MEE/TrvJAVAPYWI/AAAAAAAAAuE/KoffoIdQfNk/s640/cute-kittens-in-cups-pics.jpg"/>
<img src="http://1.bp.blogspot.com/_cWcuJM9QIG4/S7rOVzM1YcI/AAAAAAAAAgQ/RJx5oR55Ekk/s640/Animal+wallpapers%252Bcat+wallpapers%252Bmobile+wallpapers%252Bpc+wallpapers%252Bmobile+themes%252Bpc+themes+15cc.jpg"/>
<div class="rotator">
<a href="http://google.com">
<img src="http://2.bp.blogspot.com/-XI9yzJrwLac/TkLKLZF_kDI/AAAAAAAACFE/PxPDRzwa4tQ/s1600/cute+cats+pictures+3.jpg"/>
</a>
<a href="http://google.com">
<img src="http://2.bp.blogspot.com/-NOD8B0m7MEE/TrvJAVAPYWI/AAAAAAAAAuE/KoffoIdQfNk/s640/cute-kittens-in-cups-pics.jpg"/>
<a>
<a href="http://google.com">
<img src="http://1.bp.blogspot.com/_cWcuJM9QIG4/S7rOVzM1YcI/AAAAAAAAAgQ/RJx5oR55Ekk/s640/Animal+wallpapers%252Bcat+wallpapers%252Bmobile+wallpapers%252Bpc+wallpapers%252Bmobile+themes%252Bpc+themes+15cc.jpg"/></a>
</div>
<label />​
</body>
</html>
The simple script should regularly switch images, but instead of that are just displayed all 3 images. And the alert message is not displayed.
I've tried to debug the code and when I remove the function Rotate(), an alert message appears on the page.
Why the function Rotate() is not working?
$.next() gets the immediate element in the set. Your set only contains visible images - i.e. only one. How could there be a next element?
Working fiddle: http://jsfiddle.net/gjzd7/
All I have done is changed the $.next() call into an $.index() request and modulo-ed it by the number of images (so you'll never get a non-existent image). Let me know if you need anything else modified to it or any explanations!
You could also cache the images in a jQuery array and iterate over them like below.
var imgs = $(".slides"); // images to be rotated
var current = 0;
function rotate( ) {
// set current to next image
current = current >= imgs.length ? 0 : current + 1;
$(".rotator").prop("src", $(imgs.get(current)).prop("src") );
setTimeout( rotate, 5000 );
}
rotate();
Example here
Use this simple script to rotate image using buttons
function rotateImage(degree) {
$('#demo-image').animate({ transform: degree }, {
step: function(now,fx) {
$(this).css({
'-webkit-transform':'rotate('+now+'deg)',
'-moz-transform':'rotate('+now+'deg)',
'transform':'rotate('+now+'deg)'
});
}
});
}
<style>
#demo-image{padding:35px 15px;}
.btnRotate {padding: 15px 20px;border:1px solid #000; background-color:#999;color: #000;cursor: pointer;}
</style>
<div style="height:600px; width:800px; background-color:#CCC; border:1px solid #000; border-radius:6px; margin-left:auto; margin-right:auto;">
<div style="width:550px; margin-left:auto; margin-right:auto;">
<label>Rotate Image:</label>
<input type="button" class="btnRotate" value="30" onClick="rotateImage(this.value);" />
<input type="button" class="btnRotate" value="60" onClick="rotateImage(this.value);" />
<input type="button" class="btnRotate" value="90"onClick="rotateImage(this.value);" />
<input type="button" class="btnRotate" value="180" onClick="rotateImage(this.value);" />
<input type="button" class="btnRotate" value="-180" onClick="rotateImage(this.value);" />
<input type="button" class="btnRotate" value="360" onClick="rotateImage(this.value);" />
</div>
<div style="width:350px; margin-left:auto; margin-right:auto; margin-top:25px;"><img src="image-rotating-script-using-jquery .jpg" id="demo-image" /></div>
</div>

Categories