On my website I've got a button which is clicked automatically by js with the loading of the website.
window.onload=function(){
document.getElementById("myBtn").click();
};
The thing I don't know how to code is that I want the button only to be auto clicked at the first visit of the page or only once an hour...
Is there a way to do it without using jquery?
CodePudding user response:
It took some time, but I think something like this will work for you. Let me know if you face any problem with this.
// Initialize an object
let obj = {};
// Trigger when DOM loads
window.addEventListener('DOMContentLoaded', () => {
// Get current Date in UNIX
let currentDate = Date.now();
// An hour in UNIX
const hour = 3600000;
// The date to reclick
let reclickDate = currentDate hour;
// If already clicked
if (localStorage.getItem('clickData')){
// Parse the JSON object from localStorage
let data = JSON.parse(localStorage.getItem('clickData'));
// The Date to Reclick
reclickDate= new Date(parseInt(data.clickTime) hour);
}
// Otherwise click now and set object JSON
else {
document.getElementById("myBtn").click();
obj.clickTime = Date.now();
localStorage.setItem('clickData', JSON.stringify(obj));
}
// Recursive Function
checkForClick(currentDate, reclickDate);
});
const checkForClick = (currentDate, reclickDate) => {
setTimeout(() => {
// If 1 hour passed
if (currentDate > reclickDate){
// Reclick
document.getElementById("myBtn").click();
// Set localStorage new data
obj.clickTime = Date.now();
localStorage.setItem('clickData', JSON.stringify(obj));
// Break function
return;
}
// Otherwise recall the function
checkForClick(currentDate 1, reclickDate);
}, 1000);
}
CodePudding user response:
Try this below code using document ready function in jQuery:
$(document).ready(function(){
$("#myBtn").trigger('click');
});