JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script>
function DisplayTag(){ 
var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML;
var counter1=0;


function executeScript(q1,counter1){

q1= document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML;

 if(q1.match(/loader.gif/)){      
 counter1=counter1+1;
         setTimeout(function() {executeScript(q1,counter1)},100); //100 milliseconds

       }else{
function showTaggedImages(){
    var refrencestring = document.getElementsByClassName('mtb-desc');
    var maindiv = document.getElementsByClassName('bucket');
    for(var i=12;i<maindiv.length;i++){
        var current_bucket = maindiv[i];
alert(current_bucket.firstChild.firstChild.innerHTML);

    }
}

showTaggedImages();

}
}
executeScript(q1,counter1);
}
DisplayTag();
</script>

After the initial page load my script is functioning correctly. However, when another link is clicked on the same page and new content is displayed, the script does not run. How can I ensure that the script runs when this new link is clicked?

Answer №1

Supposing that the <a> elements fetch content via AJAX without refreshing the whole page, make sure to add a call to AddImageTag() within the <a> tag's click event handler.

(In case they do refresh the entire page, include the same code as mentioned above in the new page as well.)

Answer №2

Your query's title & content is unique.

Reasons for script failure after navigating to a different link

The script you wrote was executed on the previous page where it was linked using <script> tag with the source attribute pointing to your script file.

However, when you navigate to a new page by clicking a link, the script may not automatically run unless that specific <script> tag references your script using the src attribute.

Loading a script upon a user-triggered event (such as a click)

If you want to load a script when a user clicks a link, you can create a <script> element and specify its source using the <src> attribute.

<a href="javascript:loadScript()">Click Here</a>
//or
<a href="#" onclick="loadScript();return false;">Click Here</a>
function loadScript(){
  var script = document.createElement('script');
  //if the script contains functions that need explicit calling
  script.onload=function(){
    functionFromNewScript()
  }
  script.src = "path/to/yourJSfile";
}

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

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

Outputting HTML using JavaScript following an AJAX request

Let's consider a scenario where I have 3 PHP pages: Page1 is the main page that the user is currently viewing. Page2 is embedded within Page1. It contains a list of items with a delete button next to each item. Page3 is a parsing file where I send i ...

The peculiar actions of the Array.function(Object.keys(Obj[0]).map()) function

In my current code implementation, I have a hard coded [0] value that is used in rendering data for a table. However, instead of rendering only the first row as expected, it is displaying all rows. I am confused as to why this is resulting in rendering al ...

When working with arrays in a programming loop, is it better to assign the value to a variable or access it directly?

When facing a complex for loop with lots of operations, what is the most efficient way to iterate through it? for ($i = 0; count($array) > $i; $i++) { $variable = $array[$i]; $price = $variable->price; OR $price = $array[$i]->price; } T ...

Looking for a way to efficiently sort through props in Next.js? Struggling with filtering data within props from componentDidMount in Next.js?

I retrieve data into the props of my component using getStaticProps. However, I need to filter this data before utilizing it in the component. Typically, I would do this in componentDidMount, but it appears that the props are populated after componentDidMo ...

When the Jqueryui dialog is closed, it effectively terminates the current JavaScript thread

Hello there, I'm currently facing an issue with closing my jQuery dialog box. The situation involves a comet connection that sends messages to my browser. My goal is to perform certain actions upon receiving a message, close the dialog, and then conti ...

Trouble with defining variables in EJS

Recently delving into the world of node development, I encountered an issue with my EJS template not rendering basic data. I have two controllers - one for general pages like home/about/contact and another specifically for posts. When navigating to /posts ...

Navigate through the document object model and identify every pair of input boxes sequentially to build a JavaScript object

Incorporating a varied number of input boxes into a view based on selections made in a combo box. For instance, selecting '1' from the combo box results in two input boxes being added to the view. Choosing '2' adds four input boxes. Ea ...

Display the div according to the $index selected from the AngularJS list

Below is the structure of my HTML code: <div class="col-md-4"> <ul class="list-group text-left"> <a href="#" class="list-group-item" ng-click="showData($index)" ng-repeat="field in Data"> {{ field.name }}</a> ...

The HTML table seems to be inexplicably replicating defaultValue values

I'm encountering an issue where, when I use JavaScript to add a new table data cell (td), it ends up copying the defaultValue and innerText of the previous td in the new cell. This is confusing to me because I am simply adding a new HTML element that ...

multiple simultaneous ajax calls being triggered

I am currently working on creating 4 cascading dropdowns, where the options in each dropdown repopulate based on the selection made in the previous one. To achieve this functionality, I decided to implement an Ajax call. The call takes the parameters, det ...

The note-taking app's JavaScript code does not currently have the capability to store notes in local storage

const noteContainer = document.querySelector(".note-container"); const createBtn = document.querySelector(".btn"); let notes = document.querySelectorAll(".input-box"); function showNotes() { noteContainer.innerHTML = localS ...

Tips for resolving a blank screen issue when attempting to render components using the `:is="component"` attribute

Working with NativeScript-Vue for Android, my goal is to display a component based on button taps. To achieve this, I am utilizing this plugin which helps in integrating a global SideDrawer for smooth navigation. The buttons within the SideDrawer are used ...

What could be causing my Mocha reporter to duplicate test reports?

I've created a custom reporter called doc-output.js based on the doc reporter. /** * Module dependencies. */ var Base = require('./base') , utils = require('../utils'); /** * Expose `Doc`. */ exports = module.exports = ...

What is the most effective method for grouping state updates from asynchronous calls in React for efficiency?

After reading this informative post, I learned that React does not automatically batch state updates when dealing with non-react events like setTimeout and Promise calls. Unlike react-based events such as onClick events, which are batched by react to reduc ...

Implementing Pagination or Infinite Scroll to Instagram Feed

Currently, I am working on creating an Instagram feed for a fashion campaign where users can hashtag their photos with a specific tag. Using the Instagram API, the script will pull all recent posts with this common tag to display on the webpage. Instagram ...

The Vue.js component was unable to retrieve the data

I am facing an issue with accessing data inside a simple component. Here is the code for my component: <template> <!-- success --> <div class="message-box message-box-success animated fadeIn" id="message-box-success"> <div cl ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

perform a JSON request in a RESTful manner

Can you explain the concept of making a RESTful JSON request? In the given scenario, when Backbone attempts to read or save a model to the server, it calls upon the function known as Backbone.sync. This function, by default, utilizes (jQuery/Zepto).ajax t ...

Download function in Express.JS failing to retrieve file

I have been working on a Node.JS server using Express to generate and download PDFs based on user input. Previously, I used the <form action=""> method to call my API, but switched to Axios due to Netlify not supporting NuxtAPI. The program ...