Making div invisible and visible using toggle in jQuery - javascript

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>

Related

jQuery hide and show effect seen at function end

Consider the following code:
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
$("button").on( 'click', function() {
$("#thediv").show();
alert('click');
});
$(document).ready(function(){
$("#thediv").hide();
})
I want the behavior to first show the div tag and then display the alert "Click". Instead the behavior works in the opposite way. Alert text is first displayed followed by the button being visible. Am i missing something ?
Can i modify the code somehow to get the desired behavior where the div is first displayed and then alert text is flashed.
Check that in jQuery.show(options) allows you to pass a PlainObject options.
And than you can use complete: A function that is called once the animation on an element is complete.
Code:
$("button").on( 'click', function() {
$("#thediv").show({
complete: function() {
alert('click');
}
});
});
$(document).ready(function(){
$("#thediv").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
It's because the alert() blocks the UI thread from updating, and that thread has not yet had time to show the element in the DOM before you call the alert().
Ideally you should use console.log() for debugging, however you can avoid this issue by putting the alert() in a setTimeout() with a very short delay.
$("button").on( 'click', function() {
$("#thediv").show();
setTimeout(function() {
alert('click');
}, 10);
});
#thediv { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv" >hola</div>
<button id="resharper">button</button>
with javascript/jQuery:
$("button").on('click', function() {
$("#thediv").show("slow", callback);
});
$(document).ready(function() {
$("#thediv").hide();
})
function callback() {
alert('click');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="thediv">hola</div>
<button id="resharper">button</button>
Add parameter to .show()

Jquery toggle not showing div after hiding

When you click 'Darrien Tu' the text on the far right disappears but it doesn't come back when you reclick the name.
https://jsfiddle.net/gkrh0ok0/1/
$("#nav_list").click(function () {
$(".sidebar-right").toggle();
});
I have check the fiddle. There is one issue in .sidebar-right
You have given margin-left:80% instead of give right:20px
This might help to solve your issue.
I have update your script code :
<script>
$(document).ready(function() {
$menuLeft = $('.pushmenu-left');
$nav_list = $('#nav_list');
$nav_list.click(function() {
$(this).toggleClass('active');
$('.pushmenu-push').toggleClass('pushmenu-push-toright');
$menuLeft.toggleClass('pushmenu-open').after($(".sidebar-right").toggle('slow'));
});
});
</script>
Add comment to this code
<script>
/*$("#nav_list").click(function() {
// assumes element with id='button'
$(".sidebar-right").toggle();
});*/
</script>

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>

a second click to close a toggle div

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.

Toggle element's class by ID

I’m trying to change the class of an element when it is clicked on from one value A to value B and then from value B back to value A when it is clicked a second time. I found some code on here that allowed me to change it once, but not a second time. (See original here).
Here is the original code:
<script type="text/javascript">
function changeClass() {
document.getElementById("MyElement").className += " MyClass";
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/g, '')
}
</script>
And here is my code:
<script type="text/javascript">
function changeClass() {
if (document.getElementByID("arrow").className == "arrowdown") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowdown(?!\S)/g, 'arrowup')
}
elseif(document.getElementByID("arrow").className == "arrowup") {
document.getElementById("arrow").className.replace(/(?:^|\s)arrowup(?!\S)/g, 'arrowdown')
}
}
</script>
$('#arrow').toggleClass('arrowup arrowdown');
Why not simply use jQuery toggleClass instead along with a id selector?
$('#arrow').toggleClass('arrowup');
$('#arrow').toggleClass('arrowdown');
And save yourself debugging and a few lines of code!
Check this FIDDLE
Its far easier with JQuery..
$(function() {
var i = 0;
$('div').on('click', function() {
i++;
if( i % 2 == 0){
$(this).addClass('arrowup').removeClass('arrowdown');
}
else{
$(this).addClass('arrowdown').removeClass('arrowup');
}
});
});​
just use jquery addClass() and removeClass() or even better the toggleClass inside your click event
<div id="elemID" class="class1">
</div>
function changeClass()
{
$("#elemID").toggleClass("class1");
$("#elemID").toggleClass("class2");
}
REF's
http://api.jquery.com/addClass/
http://api.jquery.com/removeClass/
http://api.jquery.com/toggleClass/
Cheers
I faced something similar to this today. In my code for each feature the user would express his opinion by pressing thumbs up or thumbs down. The selected thumb icon would have a brighter color, so when the user would click the thumbs up icon, the thumbs up icon would turn green and the thumbs down icon (if it were green) would turn black.
I solved it using jQuery:
$(document).ready(function () {
$('#vote-yes-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('true');
$('#1vote-yes-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-no-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
$('#vote-no-#(Model.ProductReviewId)').click(function () {
setProductReviewHelpfulness#(Model.ProductReviewId)('false');
$('#1vote-no-#(Model.ProductReviewId)').toggleClass('green');
$('#1vote-yes-#(Model.ProductReviewId)').removeClass('green').addClass('black');
});
});

Categories