The mousedown event does not seem to function properly on dynamically added text elements

When two texts are enclosed in p tags, my goal is to create an interactive function where clicking on one text causes it to move slightly and the other text to be temporarily deleted. However, when the deleted text is re-added after clicking on the first text again, the mousedown function stops working. It's worth noting that the mousedown event only works on the initially clicked text/tag upon page load, making it the only clickable element.

$(document).ready(function() {
    
    var upPoBool = false;
    
    //first part
    $('#firstPart').mousedown(function() {
        if(upPoBool == false){
            var firstPart = document.getElementById("firstPart");
            firstPart.classList.toggle("firstPartToggle");
            
            //delete second part
            $("#secondPart").remove();
            
            upPoBool = true;
            
        } else if(upPoBool == true){
            var firstPart = document.getElementById("firstPart");
            firstPart.classList.toggle("firstPartToggle");
            
            $('#firstPart:last').after('<p id="secondPart">Second part move NEW</p>');

            upPoBool = false;
        }

    });
    
    var upBaBool = false;
    
    //second part
    $('#secondPart').mousedown(function() {
        if(upBaBool == false){
            var secondPart = document.getElementById("secondPart");
            secondPart.classList.toggle("secondPartToggle");
            
            //delete first part
            $("#firstPart").remove();
            
            upBaBool = true;
            
        } else if(upBaBool == true){
            var secondPart = document.getElementById("secondPart");
            secondPart.classList.toggle("secondPartToggle");

            $('#secondPart:last').before('<p id="firstPart">First part move NEW</p>');
            
            upBaBool = false;
        }

    });
    
});
.firstPartToggle{
    margin-left: 5rem;
}

.secondPartToggle{
    margin-left: 5rem;
}


#firstPart{
    position: absolute;
    top: 2rem;
    
    z-index: 101;
}

#secondPart{
    position: absolute;
    top: 4rem;
    
    z-index: 100;
}
<html>
<head>
<meta charset="UTF-8">
<title>ClickTestFAQ</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
    <p>Something test:</p>
    <div id="testingDiv">
        <p id="firstPart">First part move</p>
        <p id="secondPart">Second part move</p>
    </div>
    
    <!--Scripts-->
    <script src="jquery.js"></script>
    
</body>
    
</html>

The tags do not overlap, so adjusting the z-index does not have any effect. I even tried placing them in separate divs but encountered the same issue.

Answer №1

The removal of an element from the DOM also removes any bound events, including the mousedown event. This means that you will need to re-add the mousedown event after recreating your element.

Here is a solution for addressing this issue:

$(document).ready(function() {
    let upPoBool = false;
    let upBaBool = false;

        const firstPartHandler = () => {
        if(upPoBool == false){
            var firstPart = document.getElementById("firstPart");
            firstPart.classList.toggle("firstPartToggle");
            
            //delete second part
            $("#secondPart").remove();
            
            upPoBool = true;
        } else if(upPoBool == true){
            var firstPart = document.getElementById("firstPart");
            firstPart.classList.toggle("firstPartToggle");
            
            $('#firstPart:last').after('<p id="secondPart">Second part move NEW</p>');
                    $('#secondPart').mousedown(secondPartHandler);

            upPoBool = false;
        }
    }

        const secondPartHandler = () => {
        if(upBaBool == false){
            var secondPart = document.getElementById("secondPart");
            secondPart.classList.toggle("secondPartToggle");
            
            //delete first part
            $("#firstPart").remove();
            
            upBaBool = true;
        } else if(upBaBool == true){
            var secondPart = document.getElementById("secondPart");
            secondPart.classList.toggle("secondPartToggle");

            $('#secondPart:last').before('<p id="firstPart">First part move NEW</p>');
                    $('#firstPart').mousedown(firstPartHandler);
            
            upBaBool = false;
        }
    }
    
    //first part
    $('#firstPart').mousedown(firstPartHandler);
    
    //second part
    $('#secondPart').mousedown(secondPartHandler);
});
.firstPartToggle{
    margin-left: 5rem;
}

.secondPartToggle{
    margin-left: 5rem;
}


#firstPart{
    position: absolute;
    top: 2rem;
    
    z-index: 101;
}

#secondPart{
    position: absolute;
    top: 4rem;
    
    z-index: 100;
}
<html>
<head>
<meta charset="UTF-8">
<title>ClickTestFAQ</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
    <p>Something test:</p>
    <div id="testingDiv">
        <p id="firstPart">First part move</p>
        <p id="secondPart">Second part move</p>
    </div>
    
    <!--Scripts-->
    <script src="jquery.js"></script>
    
</body>
    
</html>

An alternative solution could be to hide the elements instead of removing them. Here is an example:

$(document).ready(function() {
    let activeItem = null
    
    $('#testingDiv p').mousedown(function() {
        if (!activeItem) {
            $('#testingDiv p').not(this).hide()
            $(this).addClass('active')
            activeItem = $(this)
        } else {
            $('#testingDiv p').show()
            $(this).removeClass('active')
            activeItem = null
        }
    });
});
.active {
    margin-left: 5rem;
}


#firstPart {
    position: absolute;
    top: 2rem;
    z-index: 101;
}

#secondPart {
    position: absolute;
    top: 4rem;
    z-index: 100;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <head>
    <meta charset="UTF-8">
    <title>ClickTestFAQ</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
      <p>Something test:</p>
      <div id="testingDiv">
          <p id="firstPart">First part move</p>
          <p id="secondPart">Second part move</p>
      </div>
  </body>
</html>

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

Retrieving a list of selected items using React Material-UI

In my React + Material-UI frontend, there is a section where users can select items from a dropdown menu. I am looking for a way to capture the final list of items that the user selects, and allow them to delete items by clicking on a 'x'. How ca ...

Wait until a svelte store value is set to true before fetching data (TypeScript)

I have implemented a pop-up prompt that requests the user's year group. Since I have databases for each year group, I need to trigger a function once the value of userInfo changes to true. My JavaScript skills are limited, and my experience has been ...

What are some effective ways to utilize localstorage efficiently?

I've been working on creating a variable that stores its value across multiple pages using local storage. However, I've encountered an issue where the variable is not being saved, and there are no error messages to help diagnose the problem. Her ...

Upon the initial rendering, the console log displays a null value for the data

Currently, I am utilizing the useEffect hook to populate my state during the initial rendering phase. const [data, setData ] = useState({}); const [isLoading, setIsLoading] = useState(false); useEffect(() => { fetchData(); }, []) const fetchDa ...

Trigger functions when the window is scrolled, resized, or when the document is fully loaded

I have a few functions that need to be executed under specific conditions: window.scroll window.resize document.ready For example: <script> function myFunction1(data){ /*code*/ } function myFunction2(data){ /*code*/ } ...

How can you prevent HTML from interpreting the characters '<' and '>'?

I am adding some content through JavaScript using innerHTML in a label, but nothing is showing up. I am retrieving data from an API response. { "answer_a": "<footer>", "answer_b": "<section>", ...

How can you ensure that text in a container automatically moves to a new line and causes the container to expand downward if necessary, when

Are you searching for a way to make text inside a container wrap to a new line and have the container expand downwards if needed? Update <div class="modal hide fade" id="modalRemoveReserve" style="display:none;"> <div class="modal-header"&g ...

Ways to stop a named anchor from causing a line break

Looking at the code snippet below: <a name="top"></a> <div class="topbar"> <img src="banner.jpg" alt="The Group Company" width="100%" /> <div class="printOnly"> <center><b>Printed from www.company.com</ ...

Comparing Canvas and CSS3 for Website Development

Many discussions focus on comparing games with high levels of interaction, but my project involves a web application that manipulates objects individually. These objects can be images or text, and they can be replaced, resized, rotated, zoomed in, and dele ...

Need help resolving a JavaScript error while implementing ToolScriptManager for UpdatePanel in my project

I am attempting to register the following JavaScript code in order to add freeze functionality to a GridView. However, when trying to compile, I encounter the error message 'Microsoft JScript runtime error: 'Sys' is undefined' How can ...

Having trouble saving user input from a form to a database using axios, mongodb, and vue?

I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to succe ...

Integrating foundation-sites with webpack, unable to apply styles

Delving into the world of webpack for the first time has been quite a daunting experience! I'm attempting to set up the foundation for sites, but I feel completely lost when it comes to configuring it properly. Here is my Webpack configuration: var ...

The challenge of PHP's HTTP_REFERER

I am experiencing an issue with http_referer. In my setup, I have two files: index.php and index.html. The index.php file contains a form that, upon submission, includes information like the http_referer. On the other hand, the index.html file runs an aja ...

blending javascript and php variables within ajax requests

I am working on a simple jQuery ajax feature, where I need to combine form data retrieved by JS with some PHP variables and send them all through ajax GET method. Here's what I have: var longform = $("input:text").serialize(); $.ajax({ url: & ...

Error encountered in parsing JSON: abrupt end of data (JavaScript)

I have been working on a few functions that are responsible for parsing JSON data, both external and internal, and displaying it on a local webpage using the localStorage feature. While I have successfully displayed the external JSON data, I am running int ...

Tips for Integrating a Facebook Shop Page into Your Website

Can a Facebook shop page be integrated into a website? Any guidance on how to accomplish this task would be greatly valued. ...

Creating an array of choices using jQuery: A step-by-step guide

In a jQuery solution I found on Stack Overflow, there was code used to show a specific div block only when certain menu options are selected. While I'm not well-versed in jQuery, I believe the $.viewMap block could be optimized to avoid repeating part ...

The functionality of $http get parameters is malfunctioning

Is there a reason why this code snippet is not functioning properly? $http .get('accept.php', { source: link, category_id: category }) .success(function (data, status) { $scope.info_show = data }); On the ...

"Uploading" a picture using jQuery

I have been using this particular code snippet to display messages. setTimeout(function(){ o.html(o.html() + "Username:<br>" + msg[r] + "<br><hr>") }, 7000); It's effective in posting messages from an array and adding some st ...

Updating coordinates on Google Maps using setTimeOut with jQuery and JavaScript

I am currently working on updating the markers and users' positions every five seconds so that the users can see their live position updates. I have managed to retrieve the current coordinates and update them at the correct interval, but I am struggli ...