Jquery change variable on click - javascript

Right, what I'd like to happen is when a button (or in this case, some text) is pressed, Jquery shows a div tag that contains an image, fades out the image after 2 seconds then displays some text.
This all works nicely, however I only want it to work once.
I decided to do this by using a variable and an if statement, so the variable changes from 0 to 1 and then the button cannot be clicked again due to the variable being changed.
Or at least, that's the badly worded version.
Anyhow, this is what I have so far, but for some reason the variable won't change from 0 to 1 after the button has been clicked, other than that, it works well.
The JS:
$(document).ready(function(){
$("#text2").css("display","none");
$("#ltt").css("display","none");
var clicked = '0';
if(clicked == 0) {
$(".clicker").click(function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
$clicked = '1';
});
}
});
The HTML:
<div class="clicker">
click to see text
</div>
<div id="ltt">
<img src="Images/LoadingCircle.gif" width="24" height="24">
</div>
<div id="text2">
SOME TEXT
</div>

Try to use .one() in this context,
$(".clicker").one('click', function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
});

You should use .one() instead:
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
$(".clicker").one('click',function() {
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
$clicked = '1';
});

You declared the variable to
var clicked = '0';
but calling
$clicked = '1';
later on, so your variable will not be found.
Other than in PHP you don't need the Dollar $ to declare a variable, it's just a simple typo :)

well this should work :)
$(document).ready(function(){
$("#text2").css("display","none");
$("#ltt").css("display","none");
window.clicked = false;
$(".clicker").click(function() {
if(!window.clicked){
$("#ltt").fadeIn("slow");
$('#ltt').delay(2000).fadeOut('slow');
$("#text2").delay(3000).fadeIn(1000);
window.clicked = true;
}
});
});

Related

How can I observe changes to my DOM and react to them with jQuery?

I have this function where I toggle a class on click, but also append HTML to an element, still based on that click.
The problem is that now, I'm not listening to any DOM changes at all, so, once I do my first click, yup, my content will be added, but if I click once again - the content gets added again, because as far as this instance of jQuery is aware, the element is not there.
Here's my code:
(function($) {
"use strict";
var closePluginsList = $('#go-back-to-setup-all');
var wrapper = $('.dynamic-container');
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
wrapper.append(markup);
} else {
$('.plugins-container').hide();
}
});
//Below here, there's a lot of code that gets put into the markup variable. It's just generating the HTML I'm adding.
})(jQuery);
Someone suggested using data attributes, but I've no idea how to make them work in this situation.
Any ideas?
You could just do something like adding a flag and check for it before adding your markup.
var flag = 0;
$('#install-selected-plugins, #go-back-to-setup-all').on('click', function(event) {
$('.setup-theme-container').toggleClass('plugins-list-enabled');
if ( !wrapper.has('.plugins-container') ){
var markup = generate_plugins_list_markup();
if(flag == 0){
wrapper.append(markup);
flag = 1;
}
} else {
$('.plugins-container').hide();
}
});
If you want to add element once only on click then you should make use of .one() and put logic you want to execute once only in that handler.
Example :
$(document).ready(function(){
$("p").one("click", function(){
//this will get execute once only
$(this).animate({fontSize: "+=6px"});
});
$("p").on("click", function(){
//this get execute multiple times
alert('test');
});
});
html
<p>Click any p element to increase its text size. The event will only trigger once for each p element.</p>

JQuery/JS function not firing on <a>

I have five slide shows on one page and I want to be able to cycle through all of them. The slideshow is made of an UL with each a different ID, so I want to create two functions for the arrows to cycle through the slides. And I want to pass the slide ID. My code:
$(document).ready(function() {
var slides = document.querySelectorAll('#slides li');
var slidesTotal = $('#slides li').length;
var currentSlide = 1;
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide++;
if(currentSlide > slidesTotal) {
currentSlide = 1;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
$('#slides .slide' + currentSlide).hide();
currentSlide--;
if(currentSlide == 0) {
currentSlide = slidesTotal;
}
$('#slides .slide' + currentSlide).show();
//return false;
//});
}
});
<div id="slider-container">
<ul id="slides">
<?php
for ($i = 1; $i <= $amountImagesSlideshow[3]; $i++) {
echo '<li class="slide'.$i.'"><img src="'.$directories[3],$i.'.jpg" /></li>';
}
?>
</ul>
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>
Now the funny thing is, if I remove the comments where the click is on the jQuery object and comment out the function, it will work. But not this way? I don't understand.
There is a difference between onclick event and functionality of href attribute.
When you write like this:
❮
It means, you are hyper referencing(trying to redirect) to some location whenever this anchor tag is clicked.
It doesn't mean you are doing only click action. It means, you are doing click + redirection.
href = click + redirection.
whereas, your need is only click event handling. Therefore, how you are handling through jquery.
$('a').on("click",function(){
----
----
})
This will work fine.
You shouldn't be using href to try to access a javascript function. That attribute is for navigation purposes. Also, binding to a jquery click even is the better way to handle your events so you adhere to separation of concerns design patterns.
If you need to put your function call in an attribute decorator, use the onclick attribute instead and don't evaluate the function by adding the parenthesis, just reference it.
<a onclick="previousSlide" class="previousSlideArrow">❮</a>
Anchor tag is for navigation which requires Href attribute. You should not use href for event handling. Instead:
<div class="galleryPreviewArrows">
❮
❯
</div>
It is strange..But writing that function outside document.ready works. It looks like that function should be defined before document is ready.
That may be the reson alert works always..which is a built-in function.
Also this is not the recommended way to bind event listner. Use jquery on/off to add/remove listners.
function nextSlide() {
//$('a.nextSlideArrow').click(function() {
alert('next');
//return false;
//});
}
function previousSlide() {
//$('a.previousSlideArrow').click(function() {
alert('prev');
//return false;
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<div class="galleryPreviewArrows">
❮
❯
</div>
</div>

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

Re-run javascript code when the value changes

I have two files: a html file (with the code below) and a javascript file (it creates a value for the <span id="quantity">) The code works fine, but the word only changes if I refresh the whole page.
I want the word to change from 'articles' to 'article' or vice versa as soon as the 'quantity' changes. Is this possible? And if so, how?
<span id="quantity" class="simpleCart_quantity"></span>
<span id="quantityText"></span>
<script type="text/javascript">
$(window).load(function()
{
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
});
</script>
You might want to look into MVVC framework like Knockout JS. For example, you would set the contents of the #quantity <span></span> element to be an observable.
However, try reading this SO thread to find a solution similar to what you probably are hoping for. In summary, change events only occur from the browser on the blurring of form fields, so you'll need to implement a $("#quantity").trigger('change')
Once you have a trigger set-up after the DOM element has been loaded, you can do the following:
$('#myParentNode').on('change','#mynum', function() {
// Add your logic in here
$('#quantityText').text('articles') .... .. .. .....
});
Normally, the span element doesn't fire a change event, so you cannot subscribe to it, like you would normally do in an input element.
However, you can trigger such an event using jQuery in the same code, which changes the value of the span (I assume there is such code, because normally spans don't change value).
Here is an example which simulates this change every 10 seconds, and triggers the change event. It also includes a handler for that change event, which duplicates the value in the other span.
<span id="quantity" class="simpleCart_quantity">1</span>
<span id="quantityText"></span>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var quantity = $("#quantity"),
quantityText = $("#quantityText");
setInterval(function() {
var currentVal = parseInt(quantity.html());
if (currentVal >= 10) {
quantity.html(1);
}
else {
quantity.html(currentVal + 1);
}
quantity.trigger('change');
}, 10000);
quantity.on('change', function(sender, args) {
quantityText.html($(this).html());
});
});
</script>

How to execute .click() code when previous click binding finishes

I am trying to use a Twitter Bootstrap button group with data-toggle="buttons-radio" in my site. Bootstrap markup as follows.
<div class="btn-group program-status" data-toggle="buttons-radio">
<button class="btn">All</button>
<button class="btn">Active</button>
<button class="btn">Planning</button>
<button class="btn">End of Life</button>
<button class="btn">Cancelled</button>
</div>
I need to redirect to the same page with query depending on the pressed button. I tried to use following jQuery code to achieve this.
<script>
var sParamStr = '';
function addToParamStr(str) {
sParamStr += str;
}
function redirectToUpdatedLocation() {
$('.program-status > .btn.active').each(function () {
addToParamStr( '?status=' + $(this).text());
});
console.log(sParamStr);
window.location.href = "program" + sParamStr;
}
$document.ready(function () {
$('.program-status > .btn').on('click', function (e) {
redirectToUpdatedLocation();
});
});
</script>
But the browser always redirects to {site}/program without the query string. By commenting out window.location.href = "program" + sParamStr; line, I managed to observe that second click onwards, sParamStr getting appended properly.
It seems that, my code tries to read the text of the pressed button before, .button('toggle') method form bootstrap.js finished. Code worked as intended when I changed function as follows.
$document.ready(function () {
$( '.program-status > .btn').on('click', function (e) {
$(this).addClass('active');
redirectToUpdatedLocation();
});
});
While this method works for me right now, I would like to know the proper way to achieve this. i.e How to execute my code after previous click binding finishes?
UPDATE:
I found this link in the Twitter Bootstrap forum. Seems it is a known issue.
https://github.com/twitter/bootstrap/issues/2380
I'm not sure what Bootstrap's .toggle is doing exactly, but it seems like it does some sort of animation that completes with the setting of the active class. You can try enqueing your code instead:
$( '.program-status > .btn').on('click', function (e){
$(this).queue(function (next) {
redirectToUpdatedLocation();
next();
});
});
For example, click the div as it is being toggled: http://jsfiddle.net/9HwYy/
It also seems a bit silly to me to update every href instead of just the one you clicked on since you are changing the window location anyway.
try
$('.program-status > .btn.active').each(function(i,v){
v = $(v);
addToParamStr( '?status=' + v.text());
});
since im not sure "this" is working in your case.

Categories