Perform different actions with a button based on the data attribute - javascript

I have one button. His first action is to stop a video. Then it's icon change and data-status too. His second action is to reload the page.
The problem is that I can't do the second even if I code some conditions. Sometimes it don't do anything, sometimes the second action comes at the same time of the first one.
Here is my Jquery code:
// STOP VIDEO (ACTION 1)
$("#button").click(function(){
$('#button').attr({
src: 'img/film.png',
'data-status':'stop'
});
});
// RELOAD (ACTION 2)
$("#button[data-status='stop']").click(function() {
location.reload();
});
// OTHER METHOD FOR RELOAD (ACTION 2)
if ($("#button").data( "status", "stop" )) {
$("#button").click(function() {
location.reload();
});
}
Here is my HTML code:
<img id="button" src="skip.png" data-status="play">
Can you help me?

By binding the click event multiple times, you're firing both the functions on the second click. Instead, you should put the logic that decides to stop/reload inside the one event callback:
$("#button").click(function(){
var button = $(this);
if(button.attr('data-status') === 'stop') {
// Already stopped
location.reload();
} else {
// Stop
button.attr({
src: 'img/film.png',
'data-status':'stop'
)};
}
)};

Related

How to set on change as a default on page load jquery?

I have created a on change method for a select box of my project. On selecting particular option it is basically showing and hiding a div which is perfectly working fine. Now, my problem is when first time page is loading this show and hide not working for first default section of form. Can I make this onchange function also working when page load first time.
$('.contact-form').on('change', (e) => {
var selectedId = $(e.currentTarget).val();
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
});
Here you go with a solution
function changeMethod(selectedId) {
var listofforms = $("#discount").data("display-for").split(",");
if (listofforms.indexOf(selectedId) !== -1) {
$("#discount").collapse('show');
}
else {
$("#discount").collapse('hide');
}
}
changeMethod($('.contact-form').val())
$('.contact-form').on('change', (e) => {
changeMethod($(e.currentTarget).val());
});
You need to move your code outside the change event, so I have kept your existing code within a method changeMethod.
Then call the method from to places
From you change event method
OnLoad of the JS file
Is it possible can I make my on change trigger on page load
Yes, you will just need to change your on change event from e.currentTarget to this as on page load e.currentTarget will be null, but this always points to the current element like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
});
and to trigger this change event on page load, simply add .change() at last like:
$('.contact-form').on('change', function() {
var selectedId = $(this).val();
// Your other logic here
}).change(); //<---- here

jQuery preventing click event to be executed in case of double or multiple clicks by user

I have some code in which I want to stop user from clicking a button multiple times. I have tried multiple things including disabling button on click and enabling it at the end but nothing is working perfectly.
I want to stop "click" event of jQuery (single click) from being executed in case user has clicked on it two or more times.
This is my js fiddle: https://jsfiddle.net/tm5xvtc1/6/
<p id="clickable">Click on this paragraph.</p>
<p id="main">
I will change on clicking
</p>
$("#clickable").click(function(){
$('#main').text('Single click');
});
$("#clickable").dblclick(function(){
$('#main').text('Double click')
});
If i try double clicking, the behavior is:
Single click gets executed first => Then double click gets executed.
I want to prevent single click event to be executed in case user clicks on button multiple times. Suggestions?
According to the jquery documentation:
It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.
That being said, you can accomplish what you want by using $('#main').addClass('clicked-once'); and testing for the existence of that class before executing the code inside the single click handler.
$("#clickable").click(function(){
if($(this).hasClass('clicked-once')){
return false;
} else {
$(this).addClass('clicked-once');
$('#main').text('Single click');
}
});
$("#clickable").dblclick(function(){
$('#main').text('Double click')
});
jsfiddle: https://jsfiddle.net/nbj1s74L/
This is bit tricky. You need to calculate the time taken for double click and trigger events. Try the below code
$(function() {
var clicks = 0;
var timer = null;
$("#clickable").on("click", function(e) {
clicks++; // Increment click counter
if (clicks === 1) {
timer = setTimeout(function() {
$('#main').text('Single click');
clicks = 0; //Reset
}, 800); // Increase or decrease if there is slowness or speed
} else {
clearTimeout(timer); //prevent single-click action
$('#main').text('Double click')
clicks = 0; // Reset
}
});
$("#clickable").on("dblclick", function(e) {
e.preventDefault(); //Prevent double click
});
});
Demo : https://jsfiddle.net/cthangaraja/e9e50jht/2/
I found the answer for this.
$(document).on('click', '#clickable', function () {
$(this).prop('disabled', true);
//LOGIC
setTimeout(function () { $(this).prop('disabled', false); }, 500);
});
Its working for me. The set timeout for 500ms doesn't allow code to be re-entrant which is working fine for me at various network/device speeds.
Slight change in the answer given by maverick.
In the set timeout method, reference of this is changed. Hence the code should be changed to:
$(document).on('click', '#clickable', function () {
var self = this;
$(this).prop('disabled', true);
//LOGIC
setTimeout(function () { $(self).prop('disabled', false); }, 500);
});
window.numOfClicks = 0
$("#clickable").click(function(){
window.numOfClicks += 1;
//rest of code
});
Record the number of clicks to use for your functions, example:
if (window.numOfClicks > 1){ //do this}
If you need it reset just put a timeout in the .click()
var resetClicks = function(){ window.numOfClicks = 0 }
$("#clickable").click(function(){
//your other code
setTimeout(resetClicks,5000); //reset every 5 seconds
});

OR condition for running function

I have button (".moreAlertsBtn") that run function when user click on it
I would like to run the same function if user click on another button that contain the id "#alertsBtn"
how do I add OR condition?
$(document).on('click','.moreAlertsBtn',function() { }
also - inside the function, can i add contision if user click on the first button and another if he click on the second?
Just separate them using comma(,) like this:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
can i add condition if user click on the first button and another if
he click on the second?
$(document)
.on('click','.moreAlertsBtn, #alertsBtn',function() {
if($(this).hasClass('moreAlertsBtn')) {
//.moreAlertsBtn clicked
} else {
//#alertsBtn clicked
}
});
how do I add OR condition?
You can use the comma, which in CSS is "or" (but keep reading):
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() { });
But:
also - inside the function, can i add contision if user click on the first button and another if he click on the second?
If you're going to do that, then it makes more sense to use separate handlers:
$(document).on('click','.moreAlertsBtn',function() { });
$(document).on('click','#alertsBtn',function() { });
But answering the question, yes, you can tell like this:
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
E.g.:
$(document).on('click','.moreAlertsBtn, #alertsBtn',function() {
if (this.id === "alertsBtn") {
// It's #alertsBtn
} else {
// Must be .moreAlertsBtn
}
});
That works because jQuery will call your handler with this referring to the DOM element you "hooked" the event on (even when you're actually doing delegation, as you are in your examples).
You can use comma in-between selectors as follows :
$(document).on('click','.moreAlertsBtn,#alertsBtn',function() { }

Changing jQuery Event from click to on load

I am using the following onclick function that triggers the object to become full screen when clicked. I want the object to be fullscreen when the page loads without having to click.
fbNav.find('ul li.fullscreen').on('click', function(e){
if(!fullscreen) {
fbFullscreen.show();
fbFullscreen.append(fbCont);
$window.trigger('resize');
} else {
fbParent.append(fbCont);
fbFullscreen.hide();
$window.trigger('resize');
}
fullscreen = !fullscreen;
});
How can i achieve this?
You better put the main logic in a function and call the same function on ready and click.
function fullscreen(){
if(!fullscreen) {
fbFullscreen.show();
fbFullscreen.append(fbCont);
$window.trigger('resize');
} else {
fbParent.append(fbCont);
fbFullscreen.hide();
$window.trigger('resize');
}
fullscreen = !fullscreen;
}
//will be executed when page loads
$(document).ready(function(){
fullscreen();
});
//will be executed on click
fbNav.find('ul li.fullscreen').on('click', function(e){
fullscreen();
});
You can trigger click event on page load.
fbNav.find('ul li.fullscreen').trigger("click");

Registering jQuery click, first and second click

Is there a way to run two functions similar to this:
$('.myClass').click(
function() {
// First click
},
function() {
// Second click
}
);
I want to use a basic toggle event, but .toggle() has been deprecated.
Try this:
$('.myClass').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
// odd clicks
} else {
// even clicks
}
$(this).data("clicks", !clicks);
});
This is based on an already answered question: Alternative to jQuery's .toggle() method that supports eventData?
Or this :
var clicks = 0;
$('.myClass').click(function() {
if (clicks == 0){
// first click
} else{
// second click
}
++clicks;
});
this I worked for my menu
var SubMenuH = $('.subBoxHederMenu').height();
var clicks = 0;
$('.btn-menu').click(function(){
if(clicks == 0){
$('.headerMenu').animate({height:SubMenuH});
clicks++;
console.log("abierto");
}else{
$('.headerMenu').animate({height:"55px"});
clicks--;
console.log("cerrado");
}
console.log(clicks);
});
i don't know what you are tryin to do but we can get basic toggle by
$('.myClass').click({
var $this=$(this);
if($this.is(':hidden'))
{
$this.show('slow');
}else{
$this.hide('slow');
}
})
note: this works for endless click event for that element .. not just for two clicks (if that is what you want)
OR you can use css class to hide/show the div and use jquery.toggleClass()
In the method mentioned below We are passing an array of functions to our custom .toggleClick() function. And We are using data-* attribute of HTML5 to store index of the function that will be executed in next iteration of click event handling process. This value, stored in data-index property, is updated in each iteration so that we can track the index of function to be executed in next iteration.
All of these functions will be executed one by one in each iteration of click event. For example in first iteration function at index[0] will be executed, in 2nd iteration function stored at index[1] will be executed and so on.
You can pass only 2 functions to this array in your case. But this method is not limited to only 2 functions. You can pass 3, 4, 5 or more functions in this array and they will be executed without making any changes in code.
Example in the snippet below is handling four functions. You can pass functions according to your own needs.
$.fn.toggleClick = function(funcArray) {
return this.click(function() {
var elem = $(this);
var index = elem.data('index') || 0;
funcArray[index]();
elem.data('index', (index + 1) % funcArray.length);
});
};
$('.btn').toggleClick([
function() {
alert('From Function 1');
}, function() {
alert('From Function 2');
}, function() {
alert('From Function 3');
}, function() {
alert('From Function 4');
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" class="btn">Click Me</button>
<button type="button" class="btn">Click Me</button>
If you literally only want the first and second click:
$('.myClass').one( 'click', function() {
// First click
$('.myClass').one( 'click', function() {
// Second click
});
);
var click_s=0;
$('#show_pass').click(function(){
if(click_s % 2 == 0){
$('#pwd').attr('type','text');
$(this).html('Hide');
}
else{
$('#pwd').attr('type','password');
$(this).html('Show');
}
click_s++;
});
When You click the selector it automatically triggers second and waiting for another click event.
$(selector).click(function(e){
e.preventDefault(); // prevent from Posting or page loading
//do your stuff for first click;
$(this).click(function(e){
e.preventDefault();// prevent from Posting or page loading
// do your stuff for second click;
});
});
I hope this was helpful to you..
I reach here looking for some answers, and thanks to you guys I´ve solved this in great manner I would like to share mi solution.
I only use addClass, removeClass and hasClass JQuery commands.
This is how I´ve done it and it works great:
$('.toggle').click(function() {
if($('.categ').hasClass("open")){
$('.categ').removeClass('open');
}
else{
$('.categ').addClass('open');
}
});
This way a class .open is added to the Html when you first clikc.
Second click checks if the class exists. If exists it removes it.

Categories