Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other.

Currently, I have a function that successfully extracts the person's name from the "first_name" parameter in the URL. But before doing so, I want it to wait for a few seconds and check if another div is empty. This delay ensures that if the CMS is going to populate that div with the name, it has ample time to do so.

The process involves waiting a few seconds, examining the span element to see if it is empty, and then filling the div with the name fetched from the URL.

This is what the current implementation looks like:

HTML

<div id="firstName"></div> <!--This div will be filled if the other one is empty -->
<span merge-tag="{{lead.first_name}}"></span> <!--Check if this span is empty before populating the div -->

Javascript

// URL Parser
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return 'blank';
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// Extracting First Name from URL
var firstName = getParameterByName('first_name');

// Function to add first name to div if the span with merge-tag="{{lead.first_name}}" is empty.
function addName() {
    if ($("[merge-tag={{lead.first_name}}]").is(':empty')) {
        document.getElementById("firstName").innerHTML = firstName.toString();
    }
}

window.settimeout(addName, 5000);

The current script is not functioning as expected, and I’m seeking suggestions from anyone who might have insights into why it's not working properly.

Answer №1

Perhaps there was a simple mistake in the original question, as the settimeout method should be written as setTimeout with a capital T.

Additionally, consider enclosing {{lead.first_name}} within single quotes in the handler:

if ($("[merge-tag='{{lead.first_name}}']").is(':empty')) {
  document.getElementById("firstName").innerHTML = firstName.toString();
}

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

Guide on accessing CGI Script response using AJAX

Greetings, Here is the situation: I'm working on a login form. Once the submit button is clicked, it needs to trigger a CGI script called "someurl?userName=user&password=pwd". Depending on the response from the script, I should be able to navigat ...

How can the color of the <md-toolbar> be customized?

Here is a glimpse of how my code appears on CodePen: I am aiming to have the background color of "Sidenav Left" match that of "Menu Items", which is designated by the class .nav-theme { background-color: #34495E } I attempted to override it like this ...

Adjusting the focus of an element with jQuery based on coordinates and offset values

jQuery.fn.getCoord = function(){ var elem = $(this); var x = elem.offset().left; var y = elem.offset().top; console.log('x: ' + x + ' y: ' + y); ); return { x, y }; }; This custom jQuery funct ...

How can I trigger an event again after loading dynamic HTML content?

There is a clickable div#1 that expands another div#2. During the initial load, both div#1 and div#2 display dynamic content. However, when the dynamic data is refreshed, div#1 and div#2 are rewritten causing the expand event to no longer trigger. Any th ...

Ways to eliminate gaps between div elements with CSS

I am currently working on a webpage that consists of one main div housing two inner divs (left_menu and content), along with an additional footer div outside the main container. When viewing the page, there seems to be a noticeable gap between the footer ...

Building a nested table within a parent table in bootstrap is a breeze

Can you provide guidance on nesting tables in Bootstrap-3? Whenever I attempt it, the second table ends up being displayed after the first one. ...

What is the formula for determining the percentage of transparent area on a canvas?

In my Ionic 4 drawing app, I have incorporated an image of the number 1 on the canvas using drawImage and made the background transparent. If users (typically kids) draw outside the number 1 image, the accuracy percentage will decrease. While searching for ...

Is Jquery Steps causing interference with the datepicker functionality?

I am currently using the jquery steps plugin for creating a wizard on my website. However, I am experiencing some issues with the functionality of the datepicker and qtip inside the steps. Even after switching the .js references, the problem still persists ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...

Issue with Ajax not sending query string to ASP.NET controller

I am currently working with an Ajax function that serializes data sent from my view into a query string. Here is the code snippet: UpdateFIConfig: function ($appForm) { var valid = $appForm.valid(); //if not valid the validate plugin will take ca ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

Ways to deactivate the submit button using Cookies, sessions, or local storage

Although cookies and storage can be deleted, they can still help prevent many human spammers who are unaware of this. How can I temporarily disable the form submit button on a specific page for just one day? I want to create a code that saves "Submitted" ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

"Transferring data from Ajax to PHP with a GET request: A step-by

I have created an AJAX script that passes the user's selected value from a combo box to PHP and also handles the submit button. AJAX: <script> function sendUserData(userType) { var value = $('#userType').val(); var page=& ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

Display information from a Google Sheet onto a leaflet map based on specified categories

I am currently facing some challenges while creating a map with markers using data from Google Sheet and leaflet. Despite my efforts, I have encountered a few bugs that are proving to be difficult to resolve: Group Filtering - Although I can successfully ...

I'm encountering an issue with Regex.test

When working with the following JavaScript code... $.post(url, data, function (json) { var patt = new RegExp('/^\[{"dID":/'); if (patt.test(json)) { //output json results formatted } else { //error so o ...

Accessing fields from other sources in ng-repeat can be accomplished by utilizing special syntax within the ng-repeat directive

I have a unique challenge where I need to utilize the firstkey from one AngularJS model, firstcollection, as an index value in another collection called anothercollention. Essentially, I want to iterate over the values in anothercollention based on the k ...

Is there a built-in binding for input fields in ReactJS?

I've created a somewhat intricate form in React that, when simplified, resembles the following: var MyForm = React.createClass({ init: { data: { "MyValue" : "initial value" } }, getInitialState: function() { return this.init; }, ...