jQuery mouse click counter - javascript

I need to color a table in zebra style, and then when I click on the table, twice (not double click), it should change back to original.
My question is, how to count 2 clicks?

Demo: http://jsfiddle.net/aztVY/
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();

You can use jQuery's toggleClass function for that:
$(" ... ").click(function() {
$(this).toggleClass("someClass");
});
When clicked once, the element has the someClass class, and when clicked twice, the class is removed again.

I might be wrong, but in between the lines of your question I read that you actually ask about toggleClass() method documented here.
Add or remove one or more classes from each element in the set of
matched elements, depending on either the class's presence or the
value of the switch argument.

Related

L.DomEvent.addListener() vs on(): why does one NOT work?

I created the following jquery script to cycle through each div in my HTML using a for loop. In this for loop, I define the the div and add a listener to it:
for (var i = 0; i < 3; i++) {
// Define listing
var listing = $('div[data-rid="' + i + '"]');
// Add listener to each listing div
// See below...
}
I have tried two different ways to add a listener. The first uses L.DomEvent.addListener() as such:
L.DomEvent.addListener(listing, 'mouseover', function(e) {
// Do stuff to listing div
}
The second uses the action mouseover():
listing.mouseover(function(e) {
// Do stuff to listing div
}
The L.DomEvent.addListener approach does not work. The mouseover approach works (i.e., it triggers for each div mouseover), but the "Do stuff to listing div" code only happens to the last listing div in the for loop. For example, I might mouseover div #1, but it "does stuff" div #3.
Does anyone have an idea how I might fix this issue?
Thanks!
Jesse
Try
L.DomEvent.addListener(listing[0], 'mouseover', function(e) {
// Do stuff to listing div
}
The case is, that the element jquery returns, is an array of the elements it found. listing[0] gets the first element in said array.

Call a function as if an event called it

I have the following function:
bringToFront : function () {
"use strict";
Desktop.appZ += 1;
this.style.zIndex = Desktop.appZ;
}
This function get's called when certain elements are clicked:
appWindow.addEventListener("mousedown", Desktop.bringToFront, false);
appWindowParent.appendChild(appWindow);
However, if I add some elements to the DOM and click them, thus increasing their z-index, and then add another element, this element will appear behind the first elements, instead of in front of them. So when I add "appWindow" to "appWindowParent", I also want to call "bringToFront" on "appWindow". I need to do this without chaining the "bringToFront" function (i.e. without adding arguments).
Thanks!
By the way, I know I could just increase the z-index manually when I create the element, but I intend to do more things in the "bringToFront" function and I don't want to duplicate that code.
You can use apply() to set the value of this inside the function
appWindowParent.appendChild(appWindow);
Desktop.bringToFront.apply(appWindow);
Detect by following code if a new element is inserted into dom
$(document).on('DOMNodeInserted', function(e) {
if (e.target.id == 'someID') {
}
});

toggling between two classes jQuery = works but extra click

Sort
$(".sort").click(function (event) {
$(this).toggle(function() {
$(this).toggleClass("sortUp","sortDown");
}, function() {
$(this).toggleClass("sortDown","sortUp");
});
});
it works but I need to click once before it works.
so -
click (nothing happens), click (sortUP), click (sortDown)
I would like to remove first click.
Thank you community for the help !
Firstly, you're using toggleClass incorrectly. You appear to want to toggle sortDown and sortUp on each click. That's done with toggleClass("sortDown sortUp").
Secondly, you need your class .sort to either have sortUp or sortDown set in its class property when you load the page. e.g. <a href="#" class="sort sortDown">. This makes sure you can reason about your code (i.e. it's always true that exactly one of sortUp, sortDown are set on your div).
Thirdly, $(this).click(function() { /* code */ }) means "when somebody clicks, do /*code*/". You've wrapped your
$(this).click(function() { $(this).toggleClass("sortUp sortDown"); })
which sets up the click behaviour, in a $(".sort").click(function () { which means you are requiring an initial click on "sort" just to start the behaviour.
So the correct version is:
Sort
$(document).ready(function () {
$(".sort").click(function() {
$(this).toggleClass("sortUp sortDown");
});
});
if you dont' want to begin with a sortUp or sortDown class, do this:
Sort
$(".sort").click(function (event) {
if($(this).hasClass("sortUp") || $(this).hasClass("sortDown")){
$(this).toggleClass("sortUp sortDown");
}else{
$(this).addClass("sortUp");
}
});
It looks like you are adding the click events on the first click, also if you want to switch between sortUp and sortDown you can simply specify them both. As long as the element starts with one or the other (not both and not neither), it will swap them each time.
$(".sort").click(function() {
$(this).toggleClass('sortUp sortDown');
});
You can see this running on JSFiddle.

jQuery slideUp() content when clicked for a second time

How would I slideUp() the content only when '.areaCodeList' is clicked a second time?
$(".areaCodeList").on('click', function() {
$(this).next('.churchList').slideDown();
($this.die());
$('.churchList').slideUp();
});
You should use slideToggle()
$(".areaCodeList").on('click', function() {
$(this).next('.churchList').slideToggle();
});
Example
You may use some class to indicate it already clicked before running the code
$(".areaCodeList").on('click', function() {
if (!$(this).is('.clicked')){
$(this).addClass('clicked');
return false;
}
$(this).next('.churchList').slideDown();
$(this).die();
$('.churchList').slideUp();
});
You also may consider using attributes ($(el).attr('clicked')) instead of class and check for it later in a similar way.
Update:
The question title is really confusing and it seems that only many of us (answering the question) don't got it from the start:
Initially I got it like this:
Slide the element up if it clicked for the second time.
If it's the case than the sample I've provided is correct.
But it looks like the question is more like this:
Slide the element down on every even click and slide it up on every odd click.
If this is the case that slideToggle is the solution (as explained in epascarello's answer)
You can check if the .churchList is visible (slided down):
$(".areaCodeList").on('click', function() {
if( $(this).next('.churchList').is(':visible') === true){
$(this).next('.churchList').slideUp();
}else{
$(this).next('.churchList').slideDown();
}
});

js number +1 problem

I need click div.toggle1,control slideup, slidedown the div#text1,
click div.toggle7,control slideup, slidedown the div#text7.
here is my code, also in http://jsfiddle.net/qHY8K/ my number +1 not work, need a help. thanks.
html
<div class="toggle1">click</div>
<div id="text1">text1</div>
<div class="toggle7">click</div>
<div id="text7">text2</div>
js code
jQuery(document).ready(function() {
counter = 0;
for(i=1;i<11;i++){
(function(i){
counter = counter +1;
$('.toggle'+counter).toggle(function(){
$('#text'+counter).css('display','none');
},
function() {
$('#text'+counter).css('display','block');
});
})(i);
};
});
Lets simplify things a bit. One of the nice things about jQuery is that you can apply an event handler to many elements all at the same time. Start by adding a common classname to all of your 'toggle' divs:
HTML
<div class="toggle toggle1">click</div>
<div id="text1">text1</div>
<div class="toggle toggle7">click</div>
<div id="text7">text2</div>
Now you can use just one selector to target all of those divs. The rest is just a matter of pulling out the numeric difference in each 'toggle' div's classname:
JavaScript
jQuery(document).ready(function() {
$('.toggle').toggle(off, on);
function on() {
var i = this.className.match(/[0-9]+/)[0];
$('#text'+i).css('display','block');
}
function off() {
var i = this.className.match(/[0-9]+/)[0];
$('#text'+i).css('display','none');
}
});
I've updated your jsFiddle project. Hopefully this works out for you: http://jsfiddle.net/ninjascript/qHY8K/3/
Two solutions:
With your HTML as quoted, you can just do this:
jQuery(document).ready(function() {
$("div.toggle").click(function() {
$(this).next().toggle();
});
});
...since the div you're toggling is the next adjacent div. Note also that I'm using jQuery's toggle function to toggle the visibility.
But if it's possible that may change and you're defending against that, read on...
In your JavaScript code, you're already doing something that makes it possible to avoid the counter entirely, as knitti pointed out. But the way you're doing it creates functions unnecessarily and by using the same name (i) for both your loop counter and the argument to your anonymous function, you're making it very difficult to read and maintain that code.
So:
jQuery(document).ready(function() {
for(i=1;i<11;i++){
makeToggler(i);
}
function makeToggler(index){
$('.toggle'+index).click(function(){
$('#text'+index).toggle();
});
}
});
You can see how nice and clear that makes things, and in particular using a different name for the loop counter and the argument to makeToggler avoids confusion. And again, using jQuery's toggle function, no need for you to do it at the click level. (Also note that you don't put ; after the ending brace of a for statement.)
You don't need hard coded loop.
Preserve your current HTML and have such jQuery code instead:
$("div[class^='toggle']").each(function() {
var num = $(this).attr("class").replace("toggle", "");
$(this).toggle(function(){
$('#text' + num).css('display','none');
},
function() {
$('#text' + num).css('display','block');
});
});
This will iterate over all the <div> elements with class name starting with toggle and attach them the proper toggle function.
Updated jsFiddle: http://jsfiddle.net/qHY8K/5/
why do you introduce a new variable counter? (you should use var counter = 0; if you do).
in your function you could simply use your copied loop variable i:
for(i=1;i<11;i++){
(function(i){
$('.toggle'+i).toggle(function(){
$('#text'+i).css('display','none');
},
function() {
$('#text'+i).css('display','block');
});
})(i);
};
If your HTML has the structure as above, you could give all the toggleX elements the same class toggle and then all you have to do is:
$('.toggle').toggle(function(){
$(this).next().css('display','none');
},
function() {
$(this).next().css('display','block');
});
DEMO

Categories

Resources