Javascript's second element does not trigger a click event with similar behavior

I'm currently facing an issue with displaying and hiding notification elements based on user interaction. My goal is to have multiple popup elements appear when the page loads. Then, when a user clicks the ".alert-close" element within one of the popups, it should shrink and hide its content, leaving only the ".alert-open" element visible. Clicking the ".alert-open" element should expand it back to its original size and display the content again. This behavior is functional for each individual popup. However, I encounter a challenge when trying to handle clicks on one minimized element while another one is already closed. How can I solve this issue? I've tried using e.preventDefault() and e.stopPropagation() at the end of each query without success. I need a solution that allows me to capture clicks on any number of similar events.

In addition, there's the ".alert-kill" block which works on the second element even if the first one is minimized.

Another question arises: Is there a way to automate this process without duplicating the JavaScript code for each element with a different ID? While my test code below includes duplicate IDs for testing purposes, I recognize that writing separate JS logic for each ID is not efficient. The challenge lies in identifying the click event for individual elements with the same classes so that changes are applied correctly. By removing the IDs and focusing solely on classes, the revised code looks like follows:

<script  src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

<div class="alert-container">
    <div class="alert-popup"> 
        <a class="alert-kill" href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></a>          
        <div class="pull-left close-alert">         
            <a class="alert-close" href="#" title="click to shrink"><div class="alert-icon" style="background-image:url('new/images/alert-offer.png');"></div></a> 
            <a class="alert-open hide" href="#" title="click to expand"><div class="alert-icon" style="background-image:url('new/images/alert-offer.png');"></div></a>       
        </div>     
        <div class="row top-10 content-row">
           CONTENT 1
        </div>        
    </div>

    <div class="alert-popup"> 
        <a class="alert-kill" href="#"><i class="fa fa-times-circle" aria-hidden="true"></i></a>          
        <div class="pull-left close-alert">         
            <a class="alert-close" href="#" title="click to shrink"><div class="alert-icon" style="background-image:url('new/images/avatar.jpg');"></div></a> 
            <a class="alert-open hide" href="#" title="click to expand"><div class="alert-icon" style="background-image:url('new/images/avatar.jpg');"></div></a>       
        </div>     
        <div class="row top-10 content-row">
            CONTENT 2
        </div>        
    </div>
</div>


<script>
var state = "open" ;
$(".alert-container").on("click", ".alert-popup .alert-close", function(e){    
    e.preventDefault();
    if (state !== "open")
        return;

    var $container = $(this).closest(".alert-popup");            
    var $content = $container.find(".content-row");

    $container.css({
        "right": "-270px",
        "height": "40px",
        "transition": "all 1s ease 0s"
    });
    $content.css({
        "transform":"scale(.5)",
        "transform-origin":"0 0",
        "transition": "all 1s ease 0s"
    });

    state = "close";
    $(this).addClass("hide");            
    $(this).siblings(".alert-open").removeClass("hide");
});

$(".alert-container").on("click", ".alert-popup .alert-open", function(e){    
    e.preventDefault();
    if (state === "open")
        return;
    var $container = $(this).closest(".alert-popup");
    var $content = $container.find(".content-row");
    $container.css({
        "right": "0px",
        "height": "80px",
        "transition": "all 1s ease 0s"
    });
    $content.css({
        "transform":"scale(1)",
        "transition": "all 1s ease 0s"
    });
    state = "open";
    $(this).addClass("hide");
    $(this).siblings(".alert-close").removeClass("hide");
});

$(".alert-container").on("click", ".alert-popup .alert-kill", function(){            
    $(this).closest(".alert-popup").css("display","none");            
});
</script>

Answer №1

$(".notification-container").on("click", ".notification-popup .notification-close", function(e){           
        var status = "activated" ;
        e.preventDefault();
        if (status !== "activated")
            return;

        var $popupContainer = $(e.target).closest(".notification-popup");           
        var $popupContent = $popupContainer.find(".content-section");    
        var $alertPrompt = $popupContainer.find(".alert-show");        
        $popupContainer.css({
            "right": "-270px",
            "height": "40px",
            "transition": "all 1s ease 0s"
        });
        $popupContent.css({
            "transform":"scale(.5)",
            "transform-origin":"0 0",
            "transition": "all 1s ease 0s"
        });

        status = "deactivated";
        $(e.currentTarget).addClass("hidden");            
        $($alertPrompt).removeClass("hidden");
    });

    $(".notification-container").on("click", ".notification-popup .alert-open", function(e){            
        var status = "deactivated" ;
        e.preventDefault();
        if (status === "activated")
            return;
        var $popupContainer = $(e.target).closest(".notification-popup");           
        var $popupContent = $popupContainer.find(".content-section");
        var $alertPrompt = $popupContainer.find(".notification-close");
        $popupContainer.css({
            "right": "0px",
            "height": "80px",
            "transition": "all 1s ease 0s"
        });
        $popupContent.css({
            "transform":"scale(1)",
            "transition": "all 1s ease 0s"
        });
        status = "activated";
        $(e.currentTarget).addClass("hidden");
        $($alertPrompt).removeClass("hidden");
    });

    $(".notification-container").on("click", ".notification-popup .notification-terminate", function(e){  
        var $popupContainer = $(e.target).closest(".notification-popup");
        $($popupContainer).css("display","none");            
    });

This code snippet is fully operational and serves its intended purpose. It may prove helpful for others faced with a similar issue in the future.

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

Enhance Your Website with HTML5 Video Transition Effects

Is it possible to recreate video transition effects using HTML5 similar to the ones shown in this example: Can this be achieved across all major browsers, including Safari, Firefox, Chrome, and IE9? ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

What is the reason for the request to accept */* when the browser is seeking a JavaScript file?

The html source appears as follows: <script type="text/javascript" language="JavaScript" src="myscript.js"></script> Upon debugging the http request using Fiddler, it is evident that the browser (Chrome) sends a GET request for myscript.js wi ...

Understanding the Class Syntax in Node.js

I'm having trouble understanding how to retrieve the value from a Node JS Class [Trying to use [Symbol.iterator '']]alert(Hello, ${this.name}!); Is there another way to approach this? class User { name = "Anonymous"; sayHi() { ...

Issues with implementing KoGrid within the Durandal JS framework

How do I properly bind a koGrid in my Durandal JS view page? The code provided below is not functioning as expected. View (HTML) <div id="functiontable" class="form-actions"> <div style="height: 200px" data-bind="koGrid: ...

Customize the shadow array values in Material UI themes by utilizing the createMuiTheme function to override default

Currently, I have a customized theme for my toolkit where I am utilizing createMuiTheme to override various properties like palette, fonts, etc. One particular challenge I am facing is in minimizing the shadow array within the theme object which contains 2 ...

A guide on displaying complete text as the container width expands using Tailwind CSS and Next.js

On my platform, users have the ability to create albums and give them names of any length. When a user creates an album, it generates a div along with a link (the album's name) and two icons. I am looking to implement a feature where if a user enters ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

Is there a way to manipulate a button's toggle state using Javascript as the page loads?

I am in the process of developing a straightforward web application that allows users to customize their settings. On the settings page, there are several toggle buttons that need to have their state changed during the page load to align with the preferenc ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

Design a dynamic dropdown feature that is triggered when the chip element is clicked within the TextField component

Currently, I am facing difficulties in implementing a customized dropdown feature that is not available as a built-in option in Material UI. All the components used in this project are from Material UI. Specifically, I have a TextField with a Chip for the ...

Bug in ZURB Foundation Topbar causes incorrect highlighting of links on mobile when clicked

While utilizing the ZURB Foundation Topbar, I have encountered a bug that I find frustrating. When navigating the 2nd level drop downs and clicking on a link (li elements), the active highlight flickers to one of the elements above before taking you to the ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Strategies for positioning a fixed div at the bottom of another div

I'm in the process of creating a digital restaurant menu... I decided to format it as a popup, situated within a fixed container on top of a gray transparent overlay. However, with a large number of dishes, the content exceeds the size of the containe ...

Model change event in Backbone not triggered following model setting

I tried a different approach and used $.ajax() for an ajax file upload because I couldn't quite figure out the "backbone" way at the moment. The new picture has been successfully uploaded and the ajax request returns the new backbone model in JSON for ...

Can Angular's built-in internationalization features be used to translate bindings?

Challenge The task at hand involves integrating translations into an Angular 6 application to support static text in multiple languages. The objective is to have the ability to choose a language during the build process without requiring dynamic translati ...

Monitor the traffic on my website by implementing .htaccess restrictions

I am maintaining a website with restricted access to specific IP addresses listed in the .htaccess file. I am looking to implement a logging system that tracks unauthorized attempts to access the site. Is it feasible to record each attempt in a database? ...

Issues arise with Ninja Forms when attempting to integrate with jQuery 3.1.1

I have integrated jQuery 3.1.1 into one of our websites to support the Slick slider feature. However, after updating WordPress with the latest jQuery version, the conditional logic on the form stopped functioning properly. Ninja Forms insists that the iss ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Ordering request parameters in OAuth2 URL with npm passport can be achieved by following a specific method

I have successfully utilized Oauth2 strategies like Github and Twitter to log in to a web application using npm passport. Now, I am interested in logging in using the new global id authentication. You can explore it here ; it's really amazing. Whil ...