Just sign up for events one time

A short script was created to use ajax to load pages. Only links with the class ajax-pls should be selected.

Once an eventlistener is added, the class is removed so that the included HTML can be parsed each time.... right?

(function() {
    function addEvent(element, evnt, funct){
    if (element.attachEvent)
        return element.attachEvent('on'+evnt, funct);
    else
        return element.addEventListener(evnt, funct, false);
    }
  
  var link_click = function (e) {
      e.preventDefault();
      if (this.getAttribute("href") == 'test1.html') {
        var content = document.getElementById('content');
        content.innerHTML = "<a href='test3.html' class='ajax-pls'>Test3</a>";
        register_listeners();
      } else {
        alert(this);
      }
    };
  
  function register_listeners() {
     
    var atags = document.querySelectorAll('a.ajax-pls');
    for (i = 0; i < atags.length; i++) {
      addEvent(atags[i], 'click', link_click);
      atags[i].classList.remove("ajax-pls");
    }
  }
  
  register_listeners();
})(); 

This code snippet is just for testing purposes, but is it necessary to remove the class or could I simply call register_listeners() after each inclusion?

Answer №1

Avoiding the re-adding of the same handler multiple times to each link can be achieved by removing classes before using addEvent.

One way to overcome this issue is to utilize event bubbling.

By attaching the handler to the nearest common ancestor of all the links (potentially document.body), you can capture all click events on elements within it. To handle them, you will then need to verify with event.target.

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

How can I create walls in ThreeJS using a path or 2D array?

I am faced with the task of creating a 3D house model, specifically the walls, using a 2D path or array that I receive from a FabricJS editor that I have developed. The specific type of data being transferred from the 2D to 3D views is not critical. My in ...

Is it necessary for me to indicate that I need the password from results[0] when the MySQL query only returns one result?

When querying the database and receiving only one row/result, make sure to reference the password column correctly. Use this code to ensure you are getting the correct value: var hash = results[0].password; If you try to use var hash = results.password; ...

Issue with Vue 3: Composition API does not support Array of refs

Check out the code snippet below. <template> <div v-for="item in arr" :key="item">{{ item }}</div> </template> <script> import { ref } from "vue"; export default { name: "TestArr", ...

Looking for a Hack to Integrate a Music Player into Your Website?

Currently, I am utilizing the Jplayer plugin from JQuery to incorporate an Audio player into my website. I have come across a situation where: If the user is not currently listening to any music while browsing the website, the page can load without any i ...

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

Tips for sorting an array based on various criteria from a separate array

Seeking assistance with filtering results from the data array using two arrays. var data = [{"role":"Frontend", "languages": ["HTML", "CSS", "JavaScript"]},{"role":"Fullstack", ...

"Implementing conditional rendering to hide the Footer component on specific pages in a React application

Is there a way to conceal the footer component on specific pages? app.js <div className="App"> <Header setShowMenu={setShowMenu} /> {showMenu ? <Menu navigateTo={navigateTo} setShowMenu={setShowMenu} /> : null} <Main na ...

Combine arrays using underscore or lodash

Hello, I need some assistance. I have a couple of arrays containing grades with associated classes attributes like the examples below: var arr1 = [{ "id": 53, "name": "Grade 1 AppMonkeyzTest", "classes": [{ "id": 5 ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout: https://i.stack.imgur.com/Zv4Tg.png Desired Layout: https://i.stack.imgur.com/Xuj6O.png The TextField element is displayed as follows: <TextField multiline={false} autoFocus placeholder={props.defaultAmt} ...

Next.js is constantly encountering an issue where it throws an error stating "params

I've managed to establish a successful connection between my custom server using Node.js and Express.js with Next.js. The issue I'm facing is when trying to fetch a specific car by its id upon clicking it among other cars, as I keep encountering ...

When the down key is pressed in a textarea, choose the list item

I have HTML similar to the following <div class="row"> <textarea id="txtArea" ng-model="input" ng-change="handleOnChange(input);getSearchField(input);" ng-click="search(input)" ng-focus="search(input);" ...

What is the best way to determine if a text matches any of the elements in

Seeking assistance with a demo I am working on. How can I perform a precise comparison between test and the elements in an array arr1? var arr1 = ['noël','noel']; var test = 'noel; if(){ } <script src="https://ajax.google ...

Is it possible to designate a specific position for absolutely positioned elements within a webpage?

Is it possible to specify a reference element for an absolutely positioned element in addition to its closest positioned ancestor? I am curious if there are any CSS or jQuery methods that allow for this customization. ...

Transforming a JSON string into an object within a variable amount of nested JSON structures

I'm encountering an issue with modifying JSON strings within JSON objects for varying numbers of objects. Allow me to elaborate further with my code and explanations. I have a factory that supplies JSON objects //Factory for products app.factory(&ap ...

Utilizing React.js to Sort Through JSON Data

I'm currently working with the following state: constructor(props){ super(props); this.state = { open: false, customers:[], customer:{}, products:[], product:{}, ...

How can I send two responses in a single POST request using node.js?

Below is my router setup for handling responses: questionRouter.post('/questionsReply', (req, res) => { twilioResp(req, res); var newResponse = new Response(req.body); newResponse.save((err, data) => { if (err) return handleDBError(er ...

What are the steps for utilizing functions with a variable parameter?

I have been working on a small project to practice my javascript skills, but I've run into an error that I can't seem to fix. I've tried researching a solution, but no luck so far. My goal is to create a program that generates silly insults ...

When trying to make a jQuery call using ajax, there is no response being received

I'm facing a slight issue with a gift list that is generated from SQL. My objective is to display each row as a form with a textbox and a button. When the button is clicked, I want to send the textbox value and an ID number (hidden field value) to a f ...

Can anyone offer a straightforward method for obtaining JavaScript output in Java within the Eclipse environment?

Currently, I am attempting to retrieve the return value from a JavaScript function that I have created. Although I can achieve this using a complex method involving listeners, I am interested in utilizing Eclipse's Browser.evaluate method. For practi ...