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

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

Achieving consistent scroll position when utilizing the history.js library to navigate back with the click of a button

I need help implementing a feature that allows users to return to the same position on a webpage when clicking the back button. A common example is on ecommerce sites where if you scroll down, click on a product, then go back, you should be taken back to t ...

Lacking HTML5 support, your current location cannot be accessed on Google Maps

I have implemented google maps on my basic HTML website. Currently, I am able to center the map based on the user's current location using HTML5, however this requires obtaining permission from the user. Interestingly, when I visit maps.google.com, th ...

Use the zoom feature on D3 to enhance two graphs in an HTML document

I have been experimenting with d3 libraries lately and came across http://bl.ocks.org/jroetman/9b4c0599a4996edef0ab. I successfully used it to draw a graph based on data from a tsv file and enable zoom in and out functionality, which worked well for me. Ho ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Tips for updating border color when focused with styled-components

How can I change the border color of an input on focus using styled-components and React? Here is the code snippet I am currently using: import React from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; const String ...

Store the information in the user interface of React by converting it into a file format

Currently, I am retrieving data from an API and downloading a specific file. My goal is to store this same file in the public directory within my react application. https://i.sstatic.net/bS8Z4.png this.state = { fileDownloadUrl: null, fileName ...

What is the best way to ensure uniformity in my boxes (addressing issues with whitespace and box-sizing using flexbox)?

Below is the code I have written: body { padding-top: 20px; text-align: center; background-color:black; } h1 { display: inline-block; background: white; } h1 { font-size: 30px } p { background: yellow; } .container { display: flex; ...

What is the best way to retrieve ul li values using AngularJS?

I am looking to extract the content of li elements within a ul element in an AngularJS controller and save them into an array. Sample HTML Code: <ul id="list" my-directive> <li>A</li> <li>B</li> <li>C ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...

Displaying a <div> element within a :before pseudoelement

Implementing the use of :before to insert an icon font into a div for a CSS3 hover state. I am looking to incorporate a div within the <a> tag in order for both elements to function as links: <a href="#set-4" class="column product hi-icon product ...

Varying ng-click depending on another value

When a user uploads their own photo, I resize the image, add an ng-click attribute, compile it, and append it to a new element. This process is triggered once upon photo upload: var myElement = angular.element(image); // getting the image myElement.attr( ...

Revise the cascading style sheets for HTML content loaded via AJAX

I have a situation where I am dynamically loading HTML content using AJAX with JQuery. After the content is loaded, I am triggering a click event on specific elements within the newly added HTML. However, I am encountering an issue when trying to set the ...

Positioning elements within a Bootstrap column: Fixed versus Absolute positioning

Striving to maintain the absolute positioning of the right column as users scroll through the left column has proven to be a challenging task. Despite exploring various solutions from stackoverflow and google, none seem to effectively address this issue. ...

Why is my jQuery blur function failing to execute?

Currently, I am working with HTML and the jQuery library to avoid core JavaScript in order to maintain consistency. In my project, there are 3 fields and when a user clicks on field1 and then somewhere else, I want only field1's border to turn red. T ...

What is the best way to extract the frameset from a frame window?

Here is a code snippet to consider: function conceal(frameElem) { var frameSet = frameElem.frameSet; //<-- this doesn't seem to be working $(frameSet).attr('cols', '0,*'); } //conceal the parent frame conceal(window.pa ...

Troublesome Display of Badges in Bootstrap 5

My goal is to include a badge on a label, however all it does is change the text color to white <asp:Label CssClass="badge badge-pill badge-success" ID="Label1" runat="server" Text="Label"></asp:Label> ...

Manipulating class properties in AngularJS from a controller

I won't dwell on the reason for this (it's required to override some behavior in Angular Material that is causing issues in Safari), but here is what I am attempting to accomplish: HTML: <style> .changeme{ height: 300px; } </st ...

Updating checkbox Icon in Yii2

Is there a way to customize the checkbox icon when it is checked in Yii2? Currently, I am adding a checkbox inside a div along with an icon: <i class="fa fa-check-circle icon-check-circle"></i>. However, the checkbox shows a default check symbo ...

Issue with Browsersync functionality in Docker

My Node.js app is facing an issue with Gulp, Browsersync, and Docker. When I run gulp watch locally, everything functions correctly. However, when I utilize docker-compose up, I encounter an error Cannot GET / The Browsersync UI on port 3001 is operat ...