automatically clicking a button in javascript - javascript

I have this button:
<button class="btn btn-primary" type="button">Display</button>
and I'd like to click automatically that button every 100ms, I wrote this script but it doesnt work:
window.onload = function(){
var button=document.getElementsByClassName("btn btn-primary");
setInterval(function(){
button.click();
}, 100);
)

getElementsByClassName return a NodeList instead of an Element. Try to use querySelector
window.addEventListener('load', function () {
var button = document.querySelector(".btn.btn-primary");
setInterval(function () {
button.click();
}, 100);
});
If you want apply with all matched buttons, you can use querySelectorAll and [].slice.call to convert NodeList to Array
window.addEventListener('load', function () {
var buttonList = document.querySelectorAll(".btn.btn-primary");
var buttons = [].slice.call(buttonList);
setInterval(function () {
buttons.forEach(function (button) {
button.click();
});
}, 100);
});

For making a button click automatically, it is better to pass the function in setInterval Method.
setInterval(function(){
alert('Working fine'); //Same function as it was supposed on click
}, 5000);
To see the working model, I have attached a JS Fiddle to it.
https://jsfiddle.net/xrefwqcj/2/

Many selectors can yield multiple results, so you must specify an index to work with a selected element. If there is only one result the index will be [0].
window.onload = function(){
var button=document.getElementsByClassName('btn btn-primary')[0];
setInterval(function(){
button.click();
}, 100);
}
Also if this script runs before your button has loaded, the selector will not yield any results and could produce an error - here is one solution for that:
window.onload = function(){
setInterval(function(){
if (typeof document.getElementsByClassName('btn btn-primary')[0]!="undefined"){
document.getElementsByClassName('btn btn-primary')[0].click();
}
}, 100);
}
The above script will repeatedly check whether the selected element is defined before clicking it (then continue to do so indefinitely since you don't have any mechanism to toggle it off). You also had a ")" at the last line of your sample code which I think should have been a "}".

Related

Is there a way to call jquery functions on another object after finishing the first?

I want to fade out object 1 and after fade out remove a class and add one. After that on another object the object 2 should fadein and then i assign it a class. The problem that i encountered is that if i fire my event faster than the fadein/fadeout the object stays active.
$('.menuA').on("click", function () {
$('.menuA').removeClass("blue accent-3 z-depth-2", 100);
let clicked = $(this);
$('.menuA').promise().done(function () {
clicked.addClass("blue accent-3 z-depth-2", 100);
})
animatePanes($(this).attr("con"));
})
function animatePanes(pane) {
let paneOld = $('.pane-active');
paneOld.fadeOut(250).removeClass("pane-active").addClass("pane-inactive").promise().done(function () {
$('.' + pane).fadeIn(250).removeClass("pane-inactive").addClass("pane-active");
});
};
Thats my event with the function. The problem is that if i click to fast and trigger the event on menuA the paneOld doesnt get the class pane-inactive.
I already tried to do a global variable that checks if the event is running but it didnt worked (probably because i thinked wrong).
Is there a way to disable the event listener until the event is completly finished?
Or is there a better way?
You can surely do it with a global variable - as you've already said. Maybe you just put in in the wrong place.
I'd recommend something like isAnimating=false and 'disable' the click event listener if it's value is true. This way you can reset isAnimating to false as soon as all your animations are completed.
var isAnimating = false;
$('.menuA').on("click", function() {
if (!isAnimating) {
$('.menuA').removeClass("blue accent-3 z-depth-2", 100);
let clicked = $(this);
$('.menuA').promise().done(function() {
clicked.addClass("blue accent-3 z-depth-2", 100);
})
animatePanes($(this).attr("con"));
isAnimating = true;
}
})
function animatePanes(pane) {
let paneOld = $('.pane-active');
paneOld.fadeOut(250).removeClass("pane-active").addClass("pane-inactive").promise().done(function() {
$('.' + pane).fadeIn(250).removeClass("pane-inactive").addClass("pane-active").promise().done(function() {
isAnimating = false;
});
});
}

Get a dynamic element to change text

I have a dynamic element in my web page like this that appear when I click on an icon:
<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>
But I want to change default text that come from server (where I don't have access) with a new text.
What I tried before now is represented by:
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
Example in Google Chrome
First result is when I clicked on my icon.
Second result is when I make Inspect on the button (Ctrl+Shift+I) on the button.
And I don't understand how exactly works.
How I can fix it?
Try running this on your console:
$("[data-next-button]").text("NEW TEXT");
If it works correctly, then your timing is wrong. You are probably calling button.text before the DOM has loaded. Try wrapping your code around the ready fuction:
$(function() {
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
});
You can't select a dynamic element with jquery , try with js like
document.querySelector("[data-next-button]")
In the example below there is a setTimeout() that adds the button in the HTML dynamically in 5 seconds. Then, the setInterval() changes the text of the button and close the interval. Everything worked as you expected. I don't see any error here.
var buttonIntervalCheck = setInterval(function () {
var button = $("[data-next-button]");
if(button.length === 1) {
button.text("NEW TEXT");
clearInterval(buttonIntervalCheck);
}
}, 1000);
setTimeout(function(){
$('#ss').html(`<span class="elasticbar-item text-right text-baseline">
<button class="button primary" data-next-button="">MY TEXT</button>
</span>`);
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='ss'></div>

Jquery click handler is stuck in infinite loop

I have an handler on clicking an element. It is getting stuck in an infinite loop. How can I turn off the listener for the 2nd click in this code... so that it doesn't keep repeating.
I'm trying to automatically close the toggle after 4.5 seconds. But the close click triggers another click... and so on...
$(document).ready(function(){
$(".navbar-toggle").click(function() {
setTimeout(function () {
$(".navbar-toggle").click();
}, 4500);
});
});
Add a 'flag' variable to your code
var has_clicked = false;
$(document).ready(function(){
$(".navbar-toggle").click(function() {
if(!has_clicked){
setTimeout(function () {
has_clicked = true;
$(".navbar-toggle").click();
}, 4500);
}
});
});
$(function(){
function callback2(){
$("#test").one("click", callback1);
}
function callback1(){
console.log('hi');
setTimeout(callback2, 4500);
}
$("#test").one("click", callback1);
});
jsFiddle Demo
Is this similar to what you want?
Attach the click event which execute only once, using .one(),
do whatever you want in the callback function, and attach it again after 4.5 seconds. If you cannot even modify your code to this, please let me know, I will try to think another work around
This is what I am going with for now though I believe I will use shole's approach when I get some more time... for now this is working well.
var is_open = false;
$(document).ready(function(){
$(".navbar-toggle").click(function() {
if(!is_open){
setTimeout(function () {
is_open = true;
$(".navbar-toggle").click();
is_open = false;
}, 3500);
}
});
});

Create a Bookmarklet that clicks multiple buttons on one page

I created a bookmarklet for a site a while back that ticks multiple checkboxes on a page:
javascript:javascript:;$("input[name='unfollow[]']").attr({checked:true});
Unfortunately the UI has changed and instead of checkboxes there are buttons that need to be clicked. Here is an example of the HTML of one of the buttons:
<button class="process mode-basic Unfollow" data-verb="unfollow">Unfollow</button>
There can be up to 100 of these buttons. How do I create a bookmarklet that clicks all of these buttons? Is it possible to build up a delay between each click?
Thanks.
Assuming the page has jQuery loaded, you can click each one with a delay in between:
(function(){
var unfollowButtons = $('button.Unfollow');
var index = unfollowButtons.length-1;
unfollow();
function unfollow(){
if(index >= 0){
$(unfollowButtons[index--]).click();
setTimeout(unfollow, 500);
}
}
})();
$('button[data-verb="unfollow"]').on({
click: function() {
$('#result').append($(this).text() + ' was clicked<br/>');
}
});
$('#unfollow-all').on({
click: function() {
$('button[data-verb="unfollow"]').each(function(index) {
var el = $(this);
setTimeout(function() {
clickButton(el);
}, 500 * index);
});
}
});
function clickButton(button) {
button.click();
}
fiddle: http://jsfiddle.net/6AJNc/1/

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