This is the code that i tried below: How do you execute the click function right after redirecting the person to another page using javascript
Home page html:
<a class="whitelink" href="#" onclick="redirectcontact()">Contact Us</a>
Javascript:
function redirectcontact()
{
window.location="about.php#"; //From home page to redirect to about.php
document.getElementById("clickcontact").click(); //command to execute when on about.php
}
After redirect your script loading again, so document.getElementById("clickcontact").click()
won't be executed.
One of the solutions is to save varible in local storage or cookies
Here is example
Main page:
function redirectcontact()
{
window.location="about.php#"; //From home page to redirect to about.php
window.localStorage.setItem('click',true);
}
About.php
window.addEventListener('DOMContentLoaded',function(){
if(window.localStorage.getItem('click')) {
window.localStorage.removeItem('click');
document.getElementById("clickcontact").click();
}
})
You can add this line on the script inside about.php
window.addEventListener('DOMContentLoaded',function(){
// you can add that line here document.getElementById("clickcontact").click();
})
But for the most part my second function, redirectfaq() doesn't work
About.php
function redirectcontact()
{
window.location="about.php#";
window.localStorage.setItem('click',true);
}
function redirectfaq()
{
window.location="about.php#";
window.localStorage.setItem('click2',true);
}
window.addEventListener('DOMContentLoaded',function(){
if(window.localStorage.getItem('click')) {
window.localStorage.removeItem('click');
document.getElementById("clickcontact").click();
}
if(window.localStorage.getItem('click2')) {
window.localStorage.removeItem('click2');
document.getElementById("clickfaq").click();
}
});
index.html
<li><a class="whitelink" id="clickcontact" onclick="redirectcontact()" href="about.php">Contact Us</a></li>
<li><a class="whitelink" id="clickfaq" onclick="redirectfaq()" href="about.php">FAQ</a></li>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.