Reputation: 2070
I'm looking for some specific text on a page, then automatically clicking a button if the text exists (otherwise reloading the page after a few seconds). What I would like is to reload the page after the click has been executed (with a little delay). Here's my code which is not working:
var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("this is my text")!==-1;
el = document.querySelector(".btn.secondClass");
if(hasText && el){
el.click()
{
setTimeout(function(){
window.location.reload()
},5000);
}
}
else {
setTimeout(function(){
window.location.reload()
},5000);
}
This just seems to reload the page after 5 seconds and the click doesn't get fired. Am I missing something?
Upvotes: 0
Views: 5785
Reputation: 1102
Try this:
if (your condition = true) {
setInterval(function() {
$(".btn.secondClass").trigger("click");
window.location="";
}, 5000);
}
}
Upvotes: -1
Reputation: 6175
Assuming I understand what you're trying to achieve, you're redirecting after five seconds because that setTimeout
call is always being made. You have an if
statement but are including the setTimeout
in both blocks. Why?
setTimeout
takes either a string to evaluate or a callback function. Your callback function in this case is window.location.reload
- you don't need to wrap it in another anonymous function. Use -
setTimeout(window.location.reload, 5000);
instead.
So your simplified code would be -
if (hasText && el) {
el.click();
setTimeout(window.location.reload, 5000);
}
with no else
block.
Upvotes: 2
Reputation: 3148
Use .trigger
method to force a click. Use the following code:
var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("this is my text") !== -1;
el = document.querySelector(".btn.secondClass");
$(el).click(function() {
setTimeout(function() {
window.location.reload();
}, 5000);
});
if (hasText && el) {
$(el).trigger('click');
} else {
setTimeout(function() {
window.location.reload()
}, 5000);
}
Explanation: Bind your element's click event using .click()
. Then check your condition and if satisfied, force the button to click using .trigger()
. Since el
is DOM node, to convert it to jquery object it must be wrapped by $()
.
Upvotes: 1