Identifying Elements Generated on-the-fly in JavaScript

Currently, I am tackling the challenge of creating a box that can expand and collapse using regular JavaScript (without relying on jQuery). My main roadblock lies in figuring out how to effectively detect dynamically added elements or classes to elements after the initial page load.

To see an example of my issue, you can visit this JS Fiddle page: http://jsfiddle.net/1a518a4t/3/

Upon visiting the provided link, you'll notice that the collapse feature works initially, but fails to function properly upon trying to collapse again.

Here is the snippet of JavaScript code involved:

function test() {

    var badge = document.getElementById('test');
    var close_button = document.querySelector('.test-close');

    close_button.addEventListener("click", close_box);

    function close_box() {
        badge.style.bottom = '-70px';
        close_button.classList.add("test-open");
        close_button.classList.remove("test-close");
        var open_button = document.querySelector('.test-open');
        open_button.addEventListener("click", open_box);
    }

    function open_box() {
        badge.style.bottom = '0';
        close_button.classList.remove("test-open");
        close_button.classList.add("test-close");
    }

}
window.onload = test;

My ultimate goal is to uncover how I can replicate jQuery's on method in pure JavaScript. This method is crucial for handling dynamically created elements post-page load.

Answer №1

Utilize a single event listener and refrain from adjusting inline styles, rather switch classes:

var badge = document.getElementById('test');
var button = document.querySelector('.button');
button.addEventListener("click", function toggle_box() {
  badge.classList.toggle('opened');
  badge.classList.toggle('closed');
});
#test {
  width: 300px;
  height: 100px;
  background-color: #ccc;
  position: fixed;
  bottom: 0;
  right: 20px;
  transition: all 0.2s;
}
#test.closed {
  bottom: -70px;
}
#test > .button {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 10px;
  height: 10px;
  text-indent: -9999px;
  cursor: pointer;
  background-color: #000;
}
#test.closed > .button {
  background-color: #CE312F; 
}
<div id="test" class="opened">
  <div class="button">Test</div>
</div>

Answer №2

In the feedback, it was noted that the issue arises because the element is dynamically added, requiring delegation for the event handler to properly bind to the new element. One approach is to refer to @ExampleUser's solution for a native JavaScript implementation.

var button = document.querySelector('#example div');
button.addEventListener("click", toggle_box);
...
function toggle_box() {
    if(badge.style.top == '-50px') {
        badge.style.top = '0';
        toggleClass("example-close", "example-open");
    } else {
        badge.style.top = '-50px';
        toggleClass("example-open", "example-close");
    }
}

Fiddle Demo

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

Struggling to deploy a basic node.js application to Heroku or connect it with MongoDB

Currently, I'm facing some challenges trying to deploy a simple Twitter-like app to HEROKU or MongoDB. However, I seem to be hitting roadblocks with both platforms. With MongoDB, I encounter either an internal server error or the actual code displayin ...

Merge two arrays by matching their corresponding identifiers

I have 2 separate arrays that I need to merge. The first array looks like this: const Dogs[] = [ { id: '1', name: 'Buddy' }, { id: '2', name: 'Max' }, ] The second one: const dogAges[] = [ { id: '4&ap ...

"Utilize binding in ReactJS to maintain the correct context

I'm currently learning how to update states in ReactJS by following a tutorial. In the tutorial, I came across this line of code: this.updateLanguage = this.updateLanguage.bind(this). Although I grasp the basics of 'this' and 'bind&apos ...

"Troubleshooting: Why is my jQuery .load function returning an empty div when

Currently, I am developing a PHP control panel and I need a div in one of my PHP files to automatically refresh. After researching, I found a jQuery solution that can reload specific parts of a website automatically. However, the issue I am facing is that ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

When attempting to utilize res.sendfile, an error arises indicating that the specified path is incorrect

I am facing an issue with my Express.js server and frontend pages. I have three HTML and JS files, and I want to access my homepage at localhost:3000 and then navigate to /register to render the register.html page. However, I am having trouble specifying t ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

Achieving CSS Buttons That Change to Green When Clicked and STAY Green

I've been tasked with working on a front-end project for a website that involves buttons changing color when clicked and staying that color. Here is the CSS <style> code I have written for these specific buttons: .button { background-color ...

Troubleshooting jQuery.ajax - Why won't it function properly?

I've been struggling to get the ajax service functioning properly. I tried a simple $.get("http://google.com"), but it didn't work. Additionally, this code snippet failed as well: <html> <head> <script src="https://aja ...

Switch out the image in the dropdown and update the button once it is selected

In this scenario, I am looking to dynamically change the image in a button dropdown when it is clicked. The goal is for the dropdown image to swap and replace with the actual one upon clicking. For reference, here's the fiddle: https://jsfiddle.net/32 ...

Establishing the preset values for Material-UI toggle button group

I utilized the Material UI library to implement a button toggle widget for selecting options. Check out my codesandbox project here - https://codesandbox.io/s/50pl0jy3xk The user can interact by choosing a membership type: adult, child, or infant. Option ...

Load/run JavaScript code before sending email blade template

Is it feasible to embed and run JavaScript code in a blade template before sending an email? The challenge lies in sending users some dynamically generated images from a third-party program requested via AJAX. The current setup is as follows: //report. ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

What are the typical situations in which Node.js is commonly used?

Do you believe that a majority of node.js users primarily utilize npm? What do you think are the most prevalent use cases for node.js apart from npm? ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

Tips for triggering the button command event using JavaScript

Is there a way to activate the button command event using JavaScript? I'm not referring to the BUTTON onclick event. ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...