a second click to close a toggle div - javascript

Iā€™m using the following jQuery for hiding and showing content (toggle), as a tree navigation menu in my website. I found this code extremely useful because by clicking, it displays only one div at a time.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if ($(this).attr("id") == chosen_region) {
$(this).slideDown(200);
}
else {
$(this).slideUp(600);
}
});
}
</script>
<style type="text/css">
.city_div {display: none;}
</style>
North<br>
<div class="city_div" id="box01">Div #01</div>
Centre<br>
<div class="city_div" id="box02">Div #02</div>
South<br>
<div class="city_div" id="box03">Div #03</div>
The problem is that I can close a div only by opening another div.
How to close the div by a second click on it?

You can use slideToggle, change from slideDown to slideToggle:
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if ($(this).attr("id") == chosen_region) {
$(this).slideToggle(200); // instead of slideDown
}
else {
$(this).slideUp(600);
}
});
}

First of all, don't use inline event handlers.
<script type="text/javascript">
$(document).ready(function() {
var boxes = $('.city_div');
$('.city-toggle').click(function(e) {
var box = $(this).next();
var isHidden = box.is(':hidden');
boxes.slideUp(600);
if(isHidden) {
box.slideDown(200);
}
e.preventDefault();
});
});
</script>
<style type="text/css">
.city_div {display: none;}
</style>
North
<div class="city_div" id="box01">Div #01</div>
Centre
<div class="city_div" id="box02">Div #02</div>
South
<div class="city_div" id="box03">Div #03</div>
Also, if your links don't go anywhere meaningful, use # as the href and make sure the boxes are visible by default. (Hide them using boxes.hide(); right at the start.)
Also also, <br> isn't what you should use there. <div>s are already block-level elements. If you want more padding, give them a top margin.

try this:
$(document).ready(function(){
$('.city_div').click(function(){
$(this).hide(); //or whatever code you want to hide it
});
});
that way when you click on a div, it will hide it.

Since you are using jQuery you could try using the jQuery.toggle function.
function show_region(chosen_region) {
$('#' + chosen_region).toggle('slide');
return false;
}

Keep track of the div you have clicked last:
var globalLastClickedButtonId;
$("div.city_div").click(function() {
if (globalLastClickedButtonId == $(this).attr("id")) {
$(this).hide();
} else {
var box = $(this).next().next();
var clickedId = $(this).attr("id");
$("div.city_div").each(function() {
if ($(this).attr("id") == clickedId)
box.slideDown(200);
else
box.slideUp(600);
}
}
globalLastClickedButtonId = $(this).attr("id");
});

First, why are you using such an old version of jQuery?
Second, your JavaScript can be simplified. jQuery works on sets; you don't need the .each, or loops.
Here is a working example: http://jsfiddle.net/gibble/25P9z/
Simplified HTML:
North<br>
<div class="city_div" id="box01">Div #01</div>
Centre<br>
<div class="city_div" id="box02">Div #02</div>
South<br>
<div class="city_div" id="box03">Div #03</div>ā€‹
New JavaScript:
function show_region(e) {
var $target = $(e.target);
var chosen_region = $target.attr('data-contentDiv');
var openDiv = $('#' + chosen_region);
openDiv.slideDown(200);
$('.city_div').not(openDiv).slideUp(600);
}
Last, attach events, don't inline them in your HTML.
$('a[data-contentDiv]').click(show_region);ā€‹

Because you are using an animation it is best to keep track of the div that is currently shown. If you don't, then you will start to see multiple divs showing if you click links in quick succession.
You can use this:
$(function() {
$("a").click(function(e) {
e.preventDefault();
var selectedDiv = $("#" + $(this).attr("href"));
var hide = selectedDiv.data("shown");
$(".city_div").slideUp(600);
$(".city_div").data("shown", false);
if (hide) {
selectedDiv.data("shown", false);
}
else {
selectedDiv.data("shown", true);
selectedDiv.slideDown(200);
}
});
});ā€‹
Here is a working example

You should keep a variable with your old chosen region name
<script type="text/javascript">
var old_chosen_region="";
function show_region(chosen_region) {
$('.city_div').each(function(index) {
if (($(this).attr("id") == chosen_region)&&(chosen_region!=old_chosen_region)) {
$(this).slideDown(200);
old_chosen_region=chosen_region;
} else {
$(this).slideUp(600);
}
}
old_chosen_region='';
});
</script>
This allows you to 'remember' which region you chose last and, if the chosen one equals the last you close it.
You should set old_chosen_region='' in the end to let the tab reopen.

Related

Making div invisible and visible using toggle in jQuery

I have a div where when you click it, it's suppose to turn invisible, and when you click on it again, it's suppose to turn visible. But something's wrong with my code. Please take a look:
<div id = "id"> Hello </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
//*****************************************************************************
function toggleOnClick($id){
$("#"+$id).click(function() {
$("#"+$id).toggle(
function () {
$(this).css({visibility: "hidden"});
},
function () {
$(this).css({visibility: "visible"});
}); //end of $("#"+$id).toggle
}); //end of $("#"+$id).click(function()
} //end of function toggleOnclick($id)
//*****************************************************************************
$(document).ready(function(){
toggleOnClick("id");
});
</script>
P.S: Got my source from the accepted answer in this link: jQuery toggle CSS?
tggle() will toggle between display property so it will not retain place for element after it hides, You need to use css() with callback and update its opacity, it will retain it's place.
Update : The click event will not fire on element with visibility: hidden so you need to use opacity:0
Callback in css() is a function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. ( Taken from http://api.jquery.com/css/#css-propertyName-function )
<div id="id">Hello</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
//*****************************************************************************
function toggleOnClick($id) {
$("#" + $id).click(function() {
$("#" + $id).css('opacity', function(i, v) {
return v == 0 ? 1 : 0; //end of $("#"+$id).toggle
});
}); //end of $("#"+$id).click(function()
} //end of function toggleOnclick($id)
//*****************************************************************************
$(document).ready(function() {
toggleOnClick("id");
});
</script>

smooth transition with show/hide jquery functions on hover?

I'm using an image map and when certain part of image is hovered it show div..(like in this website http://jquery-image-map.ssdtutorials.com/) I want the div to appear with smooth transitions... here is my js code
var mapObject = {
hover : function(area, event) {
var id = area.attr('name');
if (event.type == 'mouseover') {
$('.' + id).show();
$('#'+ id).siblings().each(function() {
if ($(this).is(':visible')) {
$(this).hide();
}
});
$('#'+ id).show();
} else {
$('.' + id).hide();
$('#'+ id).hide();
$('#room-0').show();
}
}
};
$(function() {
$('area').live('mouseover mouseout', function(event) {
mapObject.hover($(this), event);
});
});
Can anyone please suggest me the changes for smooth transitions...
thanks in advance! :)
So first of all, an unrelated tip - it would be a good idea to update jQuery a bit (if there isn't anything that depends on the old version you are using). live won't be available, instead you'll need to replace it with .on, but otherwise it's a good idea.
Secondly, sounds like all you're looking for is to give hide and show some transition. You can simply replace them with fadeIn() and fadeOut(). You can also use toggle which does it all at once (though might misbehave when used with a hover, because it will flip like crazy).
Here's a small snippet that shows you how they work:
$(document).ready(function() {
var img = $('img');
$('#show').on('click', function() {
img.fadeIn();
});
$('#hide').on('click', function() {
img.fadeOut();
});
$('#toggle').on('click', function() {
img.fadeToggle();
});
});
* { font-family: sans-serif; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="show"> Show me! </button>
<button id="hide"> Hide me! </button>
<button id="toggle"> Toggle me! </button>
<br>
<br>
<img src="http://www.randomwebsite.com/images/head.jpg" />
Of course, those are just shortcut functions that use the .animate functionality, which is quite flexible on its own. Here's a link where you can read more about effects and animations in jQuery and how you can use them
Echoing what yuvi said, the 'live' function is deprecated.
I'm not sure why you have your hover function inside an object, but you could also do it like this, using fadeTo:
var mapObject = {
hover : function(area, event) {
var id = area.attr('name');
if (event.type == 'mouseover') {
$('#'+ id).fadeTo(1000, 1.0);
} else {
$('#'+ id).fadeTo(1000, 0);
}
}
};
$(function() {
$('.area').bind('mouseover mouseout', function(event){
mapObject.hover($(this), event);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="area" name="div1" style="width:20px;height:20px;background-color:#CCC;margin:5px;"></div>
<div class="area" name="div2" style="width:20px;height:20px;background-color:#CCC;margin:5px;"></div>
<div id="div1" style="width:150px;height:100px;background-color:#0F0;display:none;margin:5px;">Image Stand-in One</div>
<div id="div2" style="width:150px;height:100px;background-color:#0F0;display:none;margin:5px;">Image Stand-in Two</div>
function smooth(){
if($("#show").is(":visible")){
$("#show").hide("1000");
}
else{
$("#show").show("1000");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me<br><br>
<h1 id = "show">Shown!</h1>

sliding in and out div from right using same image - JQuery

Need some JQuery help...
I want to slide in a div from the right taking 25% of the screen width.
How can I use the same '#trigger-left a' to slide out the div? (i.e. width: 0px)
JQuery:
$(function() {
$("#trigger-left a").click(function(){
var rightCol = $("#right-col");
rightCol.animate({width:'25%'},350);
return false;
});
});
HTML:
<div id="trigger-left"><img src="images/menu-icon.png" border="0"></div>
<div id="right-col">Content right column</div>
Looking forward to your solutions!
Try this:
$(function() {
$("#trigger-left a").click(function(){
var rightCol = $("#right-col");
if(rightCol.width()==0)
{
rightCol.animate({width:'25%'},350);
}
else
{
rightCol.animate({width:'0%'},350);
}
return false;
});
});
If you mean by clicking the same link the div will slide out.
Here you are:
$(function () {
var div = $("#"right-col");
$("#trigger-left a").click(function (e) {
if ($(div).width() != 0) {
$(div).animate({width:'0px'},350);
} else {
$(div).animate({width:'25%'},350);
}
});
});
Try that if it didn't work I will edit my answer. Good luck ;)
Easiest way would be to just track what state it's in. In this way can keep direction going which may not be possible if clicked in the middle of a transition if using the widths.
$(function() {
var triggered = false;
$("#trigger-left a").click(function(){
var rightCol = $("#right-col");
if(!triggered){
rightCol.animate({width:'25%'},350);
triggered = true;
} else {
triggered = false;
rightCol.animate({width:'0%'},350);
}
return false;
});
});

Remove from inside div using jQuery

I have written a script that is supposed to render text (later a partial view) inside a div on click. I detect if div is visible or not and if not, I add text on click and make the div visible. This part works perfectly. When clicked and the div is visible I want to remove what has been added so that it wont multiply if I click it multiple times.
I get both alert - so detection of div visibility works but the text is not removed and it multiplies if I click it many times.
Here is my code - can you tell me what i am doing wrong?
<script language="javascript">
$(document).ready(function () {
$(".content").hide();
$(".heading").click(function () {
var id = $(this).attr("id");
var content = $(this).next(".content");
if (content.is(":hidden")) {
content.append("<p id='render-object'>Testing rendering on click</p>");
alert('Content is opening');
}
else if (content.is(":visible")) {
content.next("#render-object").remove();
alert('Content is closing');
}
content.slideToggle(100);
});
});
</script>
You probably want to use .find() instead of .next() when removing.
Use .html() instead of .append()
<script language="javascript">
$(document).ready(function () {
$(".content").hide();
$(".heading").click(function () {
var id = $(this).attr("id");
var content = $(this).next(".content");
if (content.is(":hidden")) {
content.html("<p id='render-object'>Testing rendering on click</p>");
alert('Content is opening');
}
else if (content.is(":visible")) {
content.find("#render-object").remove();
alert('Content is closing');
}
content.slideToggle(100);
});
});
</script>
Edit : - use .find() instead of .next() as render-object is child of content and not sibling
use .find instead of .next and use .html instead of .append
<script language="javascript">
$(document).ready(function () {
$(".content").hide();
$(".heading").click(function () {
var id = $(this).attr("id");
var content = $(".content");
if (content.is(":hidden")) {
content.html("<p id='render-object'>Testing rendering on click</p>");
alert('Content is opening');
}
else if (content.is(":visible")) {
content.find("#render-object").remove();
alert('Content is closing');
}
content.slideToggle(100);
});
});
</script>

Remove an image when mouse leaves a div

I have a 3X3 box and currently I have it so that when you hover over any one of the squares the background turns blue and then when you hover out the box reverts back to empty. I also have it so that when any of the boxes are clicked an image appears. What I am trying to accomplish now is to make it so that when the box is clicked the image will appear and when that same box is clicked again the image will disappear and so on using Jquery.
Here is what I have:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$('.divs').hover(function () {
$(this).css("background-color", "#0000EE");
console.log('hover');
}, function () {
$(this).css("background-color", "");
console.log('hoverout');
});
$('.divs').click(function () {
$(this).prepend("<img class='divimg' src=http://upload.wikimedia.org/wikipedia/commons/thumb/0/08/SMirC-cool.svg/320px-SMirC-cool.svg.png>");
console.log('divclicked');
});
});
Just check if there is an image there already
var $img = $("img", this);
if ($img.length > 0)
$img.remove();
else
$(this).prepend("<img class='divimg' src=http://upload.wikimedia.org/wikipedia/commons/thumb/0/08/SMirC-cool.svg/320px-SMirC-cool.svg.png>");
If you don't want to remove the image, you just toggle the visibility
var $img = $("img", this);
if ($img.length > 0) {
$img.toggle();
} else {
$(this).prepend("<img class='divimg' src=http://upload.wikimedia.org/wikipedia/commons/thumb/0/08/SMirC-cool.svg/320px-SMirC-cool.svg.png>");
}
Have you tried jQuery().hide() and jQuery().show()
The other option is to use CSS :hover attribute.
.divs:hover {
background-color: #0000ee;
}
Regarding click you can add images to your divs and use jQuery toggling.
HTML:
<div class="divs"><img src="..." alt=""></div>
JavaScript:
$('.divs').click(function () {
$(this).children("img").toggle();
});
Try the following code in you click function
if($('img.divimg').length == 0){
$('img.divimg').fadeOut(function(){
$(this).remove()
});
}else{
$(this).prepend("<img class='divimg' style='display:none;' src=http://upload.wikimedia.org/wikipedia/commons/thumb/0/08/SMirC-cool.svg/320px-SMirC-cool.svg.png>").fadeIn();
}
Another option is to make the remove action on the added image (when it is clicked).
var img = $('<img>')
.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/thumb/0/08/SMirC-cool.svg/320px-SMirC-cool.svg.png')
.addClass('divimg')
.css('display', 'none')
.bind('click', function(){
$(this).remove();
});
$(this).prepend(img);

Categories