JavaScript's setTimeout function seems to be malfunctioning

I have implemented a JavaScript function to expand and collapse gridview rows. Below is the script:

<script type="text/javascript">
    function divexpandcollapse(divname) {
        var div = document.getElementById(divname);
        var img = document.getElementById('img' + divname);
        if (div.style.display == "none") {
            div.style.display = "inline";
            img.src = "Img1/minus.gif";
        } else {
            div.style.display = "none";
            img.src = "Img1/plus.gif";
        }
    }
</script>

Currently, when calling this JavaScript in my gridview, it expands immediately. I would like the panel to expand slowly. Is there an error in the coding with the setTimeout function? Any assistance on how to achieve this would be greatly appreciated...

<asp:TemplateField ItemStyle-Width="20px">
    <ItemTemplate>
        <a href="JavaScript:setTimeout(divexpandcollapse('div<%# Eval("ClaimMasterId") %>'),1000);">
            <img id='imgdiv<%# Eval("ClaimMasterId") %>' width="9px" border="0" src="Img1/plus.gif"
                alt="" /></a>                        
    </ItemTemplate>
    <ItemStyle Width="20px" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>

Answer №1

The reason for the issue is that it's invoking the function, capturing the return value, and then passing that to setTimeout. What you actually want to do is call the method with setTimeout, along with the arguments. To achieve this, use this alternative syntax:

window.setTimeout(func, [delay, param1, param2, ...]);

In your specific scenario, it should look like this:

setTimeout(divexpandcollapse ,1000, 'div<%# Eval("ClaimMasterId") %>')

Do you see the distinction? With this approach, setTimeout will execute your method and provide the parameters at that time.

If you prefer not to use that syntax of setTimeout, you can wrap your method call in another function:

setTimeout(function() { divexpandcollapse('div<%# Eval("ClaimMasterId") %>') }, 1000);

Nevertheless, I personally find the first method much more readable (and less cumbersome to type).

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

Ways to display or conceal information on an aspx page depending on the roles of the current user

In my ASP.NET website, each page is filled with various content and each user that logs in has specific roles. I am looking for a way to display or hide certain page contents based on the roles of the logged-in user. How can I achieve this? By the way, I ...

Ways to retrieve every item in a JavaScript array

I am facing an issue with a variable created by Flowplayer and accessed via javascript. When I output the variable directly on the page, it simply displays 'object Object', indicating that it might be an array. Without knowing the specific names ...

Mobile video created with Adobe Animate

Currently, I am designing an HTML5 banner in Adobe Animate that includes a video element. However, due to restrictions on iPhone and iPad devices, the video cannot autoplay. As a workaround, I would like to display a static image instead. Can anyone provid ...

Updating website content dynamically using AJAX and URL manipulation without refreshing the page (Node.js)

How can I update the inventory without refreshing the page using both button events and URLs? I want to be able to update to a specific page based on the URL parameter (like /inventory/2) when it is passed to the route. Currently, my AJAX request works but ...

I need help transforming this SQL query into a LINQ query. I am having difficulty with the grouping and summing aspects

My SQL query is designed to retrieve revenue associated with various colorways IDs. select p.colorwaysid,sum(oivs.actItemvalue+oivs.custom) as revenue from Product p inner join eshakti_corp..orderitemvaluesplit oivs on p.productid = oivs.productid inner j ...

Using an if-else statement within a Vue event listener

Can this task be achieved using Vue: <button @click="(true) ? funcA : FuncB"> Click </button> In this scenario, the event is a click, however it could also involve keypress, keydown, input or any other events documented in vuejs. If ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

Issue with MiniCssExtractPlugin during compilation of the entry point build

We have integrated webpack into our deployment process to bundle resources efficiently. However, we are now facing a challenge as we aim to include the bundling of sass files through webpack in order to streamline our build process. The MiniCssExtractPlugi ...

Preventing the repeated execution of a function through the use of process.env or global variables

Deciphering buffers retrieved from my MySQL database in order to obtain a specific string required in multiple parts of my node.js Express module is proving to be a challenge. Although the decrypted string will always remain the same, calling the decrypti ...

The parameter in the function is not properly defined when clicking on KendoGrid in ASP.NET MVC

I am seeking advice on a problem I am experiencing. Within my .cshtml view, I have the following code: <a class="k-button accountSearch"></a> <div class="accountsWindow" hidden="hidden"> <div class="accountsGrid"> @Html ...

Is there support for importing named exports in the experimental ES Module loading feature of NodeJS?

Consider the code snippet below: import { publishObjectAsync, consumeObjectsAsync, createChannelAsync } from "../shared/messaging/rabbitmq" This code results in the following error message: SyntaxError: The requested module does not provide an export ...

Issues arise when attempting to compare two dates using an if statement in JavaScript and Node.js

Below is the code I am working with: var currentDate = new Date().toLocaleString(); console.log(currentDate); // output: 2018-01-15 16:39:00 var selectedDate = '2018-01-15 16:39:00'; // This date is from an HTML form input field console.log(sel ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

How to Use jQuery to Detect Audio Position in HTML

Is it possible to use the HTML5 Audio tag with an eventListener or action using Dom/jQuery to trigger an event during playback or at the end? This answer mentions currentTime but lacks examples. Pseudo code provided below. <!DOCTYPE html> <html& ...

JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. ...

What is the best way to prevent event bubbling in this particular code snippet?

$('#div1').on('click', '#otherDiv1', function(event){ //Show popup $('#popupDiv').bPopup({ modalClose: false, follow: [false, false], closeClass: 'close ...

Tips for Sending Props While Utilizing CSS Modules

I've been working with a button component that utilizes the Tailwindcss framework and css modules for some extra styling. It currently looks like this, incorporating template literal to integrate the red background styling. CSS Module: .red { back ...

Deactivated jQuery contextMenu following a mouseup event

Having an issue with my jQuery custom text-selection function disabling the contextMenu event. Here is a simple example with javascript and an html file: var markFeature = { getSelected: function(){ var t = ''; if(window.getSelectio ...

Breaking Down Particular Phrases

I am currently developing an application that necessitates the user to select a location, which will then guide them to the designated spot using Google Maps. The locations are stored as an array of JSON files. Below is an example of what the list looks li ...

Trigger the onClick event when programmatically setting it as unchecked

My issue involves resetting a form when the user uses the browser's back-button. The form consists of multiple checkboxes, each with its own onClick event. Here is an example of one such checkbox: <input onclick="GetSelectedAmount();" class="Payme ...