Toggle element's class by ID - javascript

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');
});
});

Related

show one div and hide the rest using javascript

I have this script that shows/hides a div. Could anyone please explain how I can get it to show only one div at a time?
<script>
function Show_Div(Div_id) {
if (false == $(Div_id).is(':visible')) {
$(Div_id).show();
}
else {
$(Div_id).hide();
}
}
</script>
and the link...
onClick="Show_Div(Div_1)
Thanks!
Try using this
$(document).ready(function(){
$('.parent div').hide(); // hide div's on load using parent class as a starting point
$('#nav a').click(function() { // on the anchor clicks that are inside div with id=nav
var $div = $('.parent div').eq($(this).index('#nav a')); // get the relevant div
$div.show(); // show the relevant div
$('.parent div').not($div).hide(); // hide all but the relevant div
});​
}):
if i understand your question correctly , maybe you can try this way:
<script>
function Show_Div(Div_id) {
if (false == $(Div_id).is(':visible')) {
$(this).show();
}
else {
$(this).hide();
}
}
</script>
if your use this in
$(this).show();
the only one will toggle which your click~
but in this way :
$(Div_id).show();
you will get a array of target , because the selector of Jquery will select a array of target .
hope it will help you~

Fade in and fade out text at the same location

I want to write a code which can toggle two sentences fading in and fading out. But I want to toggle the sentences at the same location ie one text fades and the other starts coming in place of the first. In this case the sentences occur one below the other. Is there any way I can do this as in html content always comes one below the other.
This is the jquery script.
<script>
$(document).ready(function(){
$(function(){
$("#hide1").hide();
while(1)
{
$("#hide2").fadeOut(3000);
$("#hide1").fadeIn(3000);
$("#hide1").fadeOut(3000);
$("#hide2").fadeIn(3000);
}
});
});
</script>
Html
<p id="hide1"> Hide 1 <p>
<p id="hide2"> Hide 2 <p>
Demo
Try like this make the queue and animate
$("#hide1").hide();
function hide1() {
$("#hide2").fadeIn(3000);
$("#hide2").fadeOut(3000, hide2);
}
function hide2() {
$("#hide1").fadeIn(3000);
$("#hide1").fadeOut(3000, hide1);
}
hide1();
OR Chaining
$("#hide1").hide();
function hide1() {
$("#hide2").fadeIn(3000).fadeOut(3000, hide2);
}
function hide2() {
$("#hide1").fadeIn(3000).fadeOut(3000, hide1);
}
hide1();
This code would react dynamically, and it does not need any changes even if you want to apply this effect for more than two p elements
$("p").hide();
function test(elem) {
elem.fadeIn(1000, function () {
elem.fadeOut(1000, function () {
test(elem.next('p').length ? elem.next('p') : $('p:first'));
});
});
}
test($('p:first'));
DEMO
Try this:
setInterval(function () {
$('#hide1').fadeOut(1000, function () {
var $this = $(this);
$this.text($this.text() == 'Hide 2' ? 'Hide 1' : 'Hide 2');
$this.fadeIn(1000);
});
}, 3000);
Toggle the text within the setInterval function.
Fiddle Demo
Use a single paragraph tag and toggle the text within it while you try to fade it in and out.
$(document).ready(function(){
$(function(){
window.setInterval(function() {
$("#hideorshow").fadeToggle(1000, "linear", function() {
$("#hideorshow").text($("#hideorshow").text() === "Hide 1" ? "Hide 2" : "Hide 1");
$("#hideorshow").fadeToggle(1000, "linear");
});
}, 2000);
});
});
Also, I would suggest you use fadeToggle() instead of fadeIn() and fadeOut().
Here is a working JSFiddle demo.

checking a class to toggle between background colours

I have replicated my issue in jsfiddle: http://jsfiddle.net/66UCX/
All I want to do is toggle between red and white when the user clicks on the td in a table. I have tried using an if statement to test for the background colour like so :
if($("#fbodytd_"+uid+"_"+row+"_"+col).css("background-color") == "rgb(255, 0, 0)"){
and that didn't work so I have tried adding and removing a class called 'active' and testing for that. Thanks.
You didn't make any binding on your function function changecream(uid, row, col).
Here is a working Fiddle:
$("table").on("click", "td", function(){
if($(this).hasClass("red")){
$(this).removeClass("red").addClass("white");
} else {
$(this).removeClass("white").addClass("red");
}
});
Edit:
Of yourse if you are only toggling between background color and a chosen color, you could simplify the "on click":
$(this).toggleClass("red");
You have to include jquery library
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
and your code look like this in $(document).ready function
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#button').bind('click', function(){
$(this).after('<span> click is active</span>');
$('span').fadeOut(1000);
});
$('#toggle').toggle(
function(){
$(this).text('rebind').removeClass('unbind').addClass('rebind');
},
function(){
$(this).text('unbind').addClass('unbind').removeClass('rebind');
}
);
if($("#toggle").hasClass("unbind")) {
$('#button').bind('click');
}
else {
$('#button').unbind('click');
}
});
</script>
If all you want is to simply change the background back and fourth (and maybe something else also). Add class like
.active
{
background-color: Red
}
and use a code like so:
$("table").on("click", "td", function() {
$(this).toggleClass("active");
});
Hope this helps.
If you are using jQuery anyway, the following simplified version should do:
$('table.bodymap td').click(function () {
$(this).toggleClass('active')
});
See this fiddle for a working example.

Remove dynamically generated div with jquery

I would like to add/remove a new div when the corresponding checkbox is checked/unchecked with jQuery. Here's my attempt:
<script type="text/javascript">
$(function() {
$("#form1 :checkbox#checkbox1").click(function() {
var d = document.createElement('div');
if ($(this).is(":checked")) {
$(d).addClass("newdiv")
.html("This is a new div")
.appendTo($("#mydiv"))
.hide()
.fadeIn(1000);
}
else {
//$(".newdiv").fadeOut(1000);
$(d).fadeOut(1000);
}
});
});
</script>
The fadeIn process comes out smoothly. But when I tried to fadeOut $(d) using the same methodology, it didn't work: the new generated div remained on the page. I did some research and get a work around, with $(".newdiv").fadeOut(1000); (commented in the code above), but that's not the best solution for me I think. And also I really want to know why my first attempt didn't work. Any suggestions? Thanks.
There are few changes you can make
1. No need for the selector #form1 :checkbox#checkbox1 since you have an id for the checkbox, you can just use #checkbox1
2. Create the div using jQuery instead of using createElement $('<div/>')
3. After fading out the div you need to remove it from the dom
$(function() {
$("#checkbox1").click(function() {
if ($(this).is(":checked")) {
$('<div/>').addClass("newdiv")
.html("This is a new div")
.appendTo($("#mydiv"))
.hide()
.fadeIn(1000);
}
else {
$('#mydiv .newdiv').fadeOut(function(){
$(this).remove()
})
}
});
});
Demo: Fiddle
Another solution is to have a static div which will be shown and hidden
$(function() {
var div = $('<div/>').addClass("newdiv")
.html("This is a new div")
.appendTo($("#mydiv"))
.hide();
$("#checkbox1").click(function() {
if ($(this).is(":checked")) {
div.fadeIn(1000);
} else {
div.fadeOut(1000)
}
});
});
Demo: Fiddle
jsFiddle Demo
Every time your click handler runs, you're creating a new variable d with a new element. Instead, do that before the click handler, so each instance will reference the same element. I have included other optional improvements below.
A change event is more appropriate for checkboxes. Also, notice I made your selector just #checkbox1, since that is already unambiguous and maximally specific.
To get a better visual effect, don't add the element, hide it, then fade it in. In most browsers that will show the element flicker before it appears. Instead, use a class to hide it with css: .hidden {display: none;}. You can also use fadeToggle to toggle the visibility, instead of doing if/else. clearQueue removes extra events for multiple clicks during a transition, and makes transitions appear smoother.
Finally, use jQuery to create the element:
$(function () {
var $d = $('<div>', {
"class": "hidden",
text: "This is a new div"
}).appendTo("#mydiv");
$("#checkbox1").change(function () {
$d.clearQueue()
.stop()
.fadeToggle(1000);
});
});
You better make d a jQuery object.
<script type="text/javascript">
$(function() {
$("#checkbox1").click(function() {
var d = $('<div class="newdiv"></div>');
if ($(this).is(":checked")) {
d.html("This is a new div")
.appendTo($("#mydiv"))
.hide()
.fadeIn(1000);
}
else {
d.fadeOut(1000);
}
});
});
</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.

Categories