Perform the script only when a click event occurs

I need help with a script that will only refresh the page when a specific link is clicked. Currently, the script is running on page load instead of waiting for the click event.

As someone who is not familiar with JavaScript, I am struggling to figure this out on my own. Any assistance would be greatly appreciated...

Edit: I made some changes to my code, but now it's not executing at all - neither on page load nor on click.

Edit 2: This issue is part of a larger problem. You can observe the effect by visiting the following website:

Once on the site, use the dropdown menu under 'productions' and select 'Edition Klangidee'. The page loads correctly and scrolls to the anchor. However, if you click 'Edition Klangidee' again, the cookie bar seems to displace all content by its own height. A simple reload fixes the layout.

The cookie bar is generated by a script that I did not create myself (as I lack the skill to do so) but downloaded.

In my opinion, the best solution would be to modify the JavaScript file. Since I lack the required knowledge, I thought an auto-reload feature could serve as a temporary workaround.

Perhaps this additional information provides some context...

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>

Answer №1

By utilizing the function, you are activating its functionality

(function fun() {

}());  <-- this is how it's executed

When creating a function, all you need is the function itself

function fun() {

}

Answer №2

Here is a straightforward solution using plain JavaScript:

    window.onload = function(e){
        console.log("window.onload: " + new Date());
    }
    function refreshPage() {
        location.reload();
    }
<a href="javascript:void(0);" target="_self" id="ek_reload" onclick="refreshPage()">Click to reload</a>

Answer №3

previously mentioned, you are invoking the function itself
if desired, another approach can be utilized such as
html

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

javascript

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

alternatively, the onclick can be removed and an event listener created like so

html

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

javascript

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


hope that was helpful:)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Bootstrap ToggleButton firing function multiple times unnecessarily

I've encountered an issue with my react-bootstrap ToggleButtons. Whenever I click on them, the handlePlatformChange() function is triggered twice - first with the correct id and then immediately after with null. I tried including e.preventDefault() in ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out. Below is the code snippet: import React from "react"; import ReactDOM from "react-dom"; import { TextField, Bu ...

Converting a string to a number is not functioning as expected

I am facing a problem with an input shown below. The issue arises when trying to convert the budget numeric property into thousands separators (for example, 1,000). <ion-input [ngModel]="project.budget | thousandsSeparatorPipe" (ngModelChange)="projec ...

Utilizing Asynchronous Values in a Different JavaScript Function

Currently delving into the world of destructuring arrays in Javascript, I find myself faced with the challenge of accessing these variables in other functions. I attempted to retrieve the array by calling a function and then using console.log(thermostatAr ...

Struggling to retrieve CSS property from a child element?

Check out this HTML snippet: <div id="ctr" class="faden-slider-container"> <div class="conteneur-image" ></div> <div class="conteneur-image" ></div> <div class="conteneur-image" ></div> </div> ...

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

Converting an Object into an Array of Objects

The question at hand is quite simple yet lacks a definitive answer. I have an object and my objective is to take each key and value pair, transform them into objects, and then push them into an array. To illustrate this, consider the example below. { tit ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...

Successfully converted Javascript variables to PHP variables, however, I faced difficulties when attempting to compare the PHP variable

When transferring a javascript variable to a php variable, it is typically done using POST or Ajax methods. The code below shows a way to convert the javascript variable to a php variable without relying on POST, Get, or Ajax. When the php variable ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

Unleashing the Power of Lodash Debounce in Vue

Currently, I have integrated debounce from lodash into my main.js file. import lodash from 'lodash' Vue.prototype._ = lodash I've been utilizing it like this._.find(...), and everything has been functioning smoothly. However, when attemptin ...

Using JavaScript to Parse JSON Data Retrieved from an AJAX Call

I am currently facing an issue with a JavaScript file that is making an AJAX call to a PHP file on the server. The PHP file returns JSON encoded data, which can either be a success or a failure depending on various conditions: if ( some condition here ) { ...

The standard date format used in Javascript/Jquery programs

I have a kendo date picker set to display dates in the format "MM/dd/yyyy". I need to use jquery or javascript to ensure that the selected date is not in the future and is greater than '01/01/1900'. The problem I'm encountering is handling ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

The issue I am experiencing within my PHP code is that the redirection to the gratitude page is not functioning correctly when utilizing

As a newcomer to PHP, I have been struggling with an example code from a website that is not redirecting to the thank you page as expected. Moreover, the email functionality is not working properly either. The code was sourced from: Upon downloading the f ...

Firestore - Using arrayUnion() to Add Arrays

Is there a way to correctly pass an array to the firebase firestore arrayUnion() function? I encountered an issue while attempting to pass an array and received the following error message: Error Error: 3 INVALID_ARGUMENT: Cannot convert an array value ...

having trouble retrieving information from the input field

I'm having trouble retrieving the user's input from the input field, can someone assist me with this issue? I can't seem to identify what the problem is here. var ftemp = document.getElementById("Farenheit").value; <td> <i ...

Transferring information between React components

After sending a request to retrieve all matching data from the database based on the answers provided in a questionnaire, I intend to utilize the data in a separate component to showcase the outcomes. <div className='row justify-content-end mt-3 p ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...