-1

I would like a page refreshing ONLY when a certain link is clicked. But in my sample the script is executed on page load, not on click on the respective element.

I am not a js-coder, but a complete noob... so please be patient with me. Any help would be greatly appreciated...

EDIT: Edited - now my code looks like that: Issue is that it is no longer executed at all, not on pageload, but also not on click

EDIT 2: It's actually part of a bigger problem: You can see the effect if you go to this website: https://www.klangidee.de/index.php?19start&lang=en

Then use the dropdown on 'productions' and click on 'Edition Klangidee'. The page loads fine and jumps to the anchor. Now if you click the 'Edition Klangidee' link a second time the cookie-bar seems to push all content up by it's own height. If you reload, everything gets back to normal.

The cookie-bar is created by script I didn't write (couldn't do that) but downloaded.

So imho the proper way to solve it would be to edit the js file. But as I do not have the knowledge to do that I thought an automatic reload (instead of the manual one) would be a suitable workaround.

Maybe that background info helps....

script:
=======

<script type="text/javascript">
    ;(function fun() {
        var reloads = [1000, 3000],
            storageKey = 'reloadIndex',
            reloadIndex = parseInt(localStorage.getItem(storageKey), 10) || 0;

        if (reloadIndex >= reloads.length || isNaN(reloadIndex)) {
            localStorage.removeItem(storageKey);
            return;
        }

        setTimeout(function(){
            window.location.reload();
        }, reloads[reloadIndex]);

        localStorage.setItem(storageKey, parseInt(reloadIndex, 10) + 1);
    }
</script>

html-code:
==========

<a href="https://mylink#myanchor" target="_self" id="ek_reload" onclick="fun()">MyMenuItem</a>
Hal
  • 13
  • 2

3 Answers3

3

You are executing the function

(function fun() {

}());  <-- this is executing it

When you define a function, you just have the function

function fun() {

}
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

I assume this is the solution you're looking for in vanilla JS:

    window.onload = function(e){
        console.log("window.onload: " + new Date());
    }
    function fun() {
        location.reload();
    }
<a href="javascript:void(0);" target="_self" id="ek_reload" onclick="fun()">MyMenuItem</a>
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28
0

as said before you are executing the function itself
if you want you can also use something like that
html

<input type="button" onclick="fun()" value="test">

javascript

 fun=()=>{
   alert("hey there");
   }

or you can remove the onclick and create event Listener like that

html

<input id="testBTN" type="button" value="test">

javascript

document.getElementById("testBTN").addEventListener("click", ()=>{alert("hey man")}); 


hope i was able to help:)

nedy
  • 61
  • 1
  • 5