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

Can an identification be included in a label element?

My inquiry is as follows: <label for="gender" class="error">Choose</label> I am interested in dynamically adding an id attribute to the above line using jQuery or JavaScript, resulting in the following html: <label for="gender" class="err ...

Can you please explain the purpose of the state object in the setSearchParams hook of react-router-dom v6

Can anyone explain the { state: ? } parameter used in the update function of useSearchParams? const [search, setSearch] = useSearchParams(); setSearch( { ...Object.fromEntries(search), transFilters: JSON.stringify(filters), }, { ...

Controlling data tables with knockout.js

I have successfully integrated an API in knockout.js, but I am facing an issue with displaying the amount based on accounting principles. My table definition includes columns for id, name, debit, credit, and amount. Since not all amounts fall under debit o ...

Choosing custom element children once they're connected to the DOM: A guide

My goal is to retrieve the value of transaction-name__inputbox when the user clicks on the transaction-add__button. The function transactionAddHandler is triggered upon clicking the button. However, my attempt to select this element using document.querySe ...

Having trouble attaching a function to a button click event

My viewModel includes a function: function resetForm(){ loanSystem("lis"); status(""); processor(""); fileType("funded"); orderDate(""); loanNumber(""); team(""); borrower(""); track ...

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

When I upgraded my "react-router-dom" from version "5.2.0" to "6.14.0", I encountered a warning stating "No routes matched location"

After updating react-router-dom from version "5.2.0" to "6.14.0", I encountered a warning saying "No routes matched location." Initially, I received an error stating that "<Route> is only meant to be used as a child of <Routes>, not rendered d ...

The three.js library is throwing an error because it is unable to access the 'geometry' property of an

function CreateNewSphere(x, z) { var sphereGeometry = new THREE.SphereBufferGeometry(10 * factor, 32, 32); var sphereMaterial = new THREE.MeshBasicMaterial({ color: SphereColor, wireframe: false }); var sphere = new THRE ...

`vue.js pagination for loading nested arrays`

I am currently working on implementing the vue-paginate component from this source: https://www.npmjs.com/package/vue-paginate . My goal is to set up pagination for questions retrieved from firebase. Here is the initial setup: new Vue({ el: '#app& ...

Ensure all fields are valid prior to performing an update

I'm currently faced with the challenge of validating my form data before executing an AJAX update. Essentially, what I want to achieve is to validate the input data in the form before triggering the ajax update function. I'm unsure about where to ...

Errors always occur when making POST requests in SAPUI5, leading to a 500 Server Error specifically related to OData

Currently diving into the world of SAPUI5 and OData, I am in the process of creating a basic application that showcases employee data in a table. The objective is to add a new employee to the table whose information will be stored in the SAP backend. Whil ...

Having trouble setting cookies with Node.js Express?

Check out this code snippet: const app = express(); const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.post("/pinfo", (req, res) => { var form = new formidable.IncomingForm(); form.parse(req, async functi ...

Tips to prevent modal impacts on underlying elements?

When I click on a button, a modal pops up. However, the background contents seem to spread out and sometimes scroll automatically when the modal appears. I have searched for a solution to this issue but have been unsuccessful. Can anyone please help me ide ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

Utilize the provided parameter within a JavaScript function

<script type="text/javascript"> function updateTrackName(trackNum) { document.form1.track_(track_number)_name.value=document.form1.track_(track_number)_parent_work.value; } </script> To modify the line inside of the parent_wor ...

The Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

Creating a 2D array matrix in JavaScript using a for loop and seamlessly continuing the number count onto the next row

I'm attempting to create a 2d matrix with numbers that continue onto the next row. var myMatrix = []; var rows = 5; var columns = 3; for (var i = 0; i < rows; i++) { var temp = 1; myMatrix[i] = [i]; for (var j = 0; j < columns; j++) ...