Jquery click event only firing once

My challenge is drawing lines between two points, although I've managed to do it once. The issue arises when I try to repeat the process; nothing happens on the second click of a circle.

Please note that this functionality only works in modern browsers

I have set up a script where clicking on circles should draw lines between them. However, I am facing an issue where the line is only drawn once and not again on subsequent clicks. Below is the code snippet: 

var click = false;
var x1;
var y1;
var x2;
var y2;
$('circle').click(function () {
    if (click == false) {
        x1 = $(this).attr('cx')
        y1 = $(this).attr('cy')
        click = true;
    } else {
        click = false;
        x2 = $(this).attr('cx');
        y2 = $(this).attr('cy')
        var x=$('<line x1="' + x1 + '" y1="' + y1 + '" x2="' + x2 + '" y2="' + y2 + '" stroke-width="30" stroke="green" stroke-linecap="round"/>')
        $('svg').append(x)
       
       $("body").html($("body").html());
    }
})
/* CSS for animation effect */
line{
    transition:.5s all;
    stroke-dasharray:2000;
    stroke-dashoffset:2000;
   -webkit-animation:move 1s forwards;
}
@-webkit-keyframes move{
    100%{
        stroke-dashoffset:0;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<svg width="800" height="800">
/* Circle elements */
    <circle cx="30" cy="30" r="30" />
    <circle cx="120" cy="30" r="30" />
    <circle cx="210" cy="30" r="30" />
    <circle cx="300" cy="30" r="30" />
<!-- Additional circle elements -->
    ...
</svg>

Note: This feature appears to work in the provided snippet, but not in the linked fiddle http://jsfiddle.net/akshay7/m2g6w80y/4/

Answer №1

Event handlers are only bound to the elements that are currently selected; they need to be present on the page when your code is binding the event.

If you are replacing content using

$("body").html($("body").html());

Then you should utilize Event Delegation with .on() delegated-events approach.

For example:

$(document).on('event','selector',callback_function)

Example:

$(document).on('click', 'circle', function () {
    //Your code
});

Instead of using document, choose the closest static container.

Delegated events have the advantage of being able to handle events from descendant elements added to the document later. By selecting an element that will definitely exist at the time the delegated event handler is attached, we can use delegated events to link the click event to dynamically generated elements and eliminate the need for frequent attachment and removal of event handlers.

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

Encountered an unexpected character "<" while looking for an identifier in a React.js project

Looking to expand my React skills, I decided to delve into a basic e-commerce project using Visual Studio. Unfortunately, I encountered some errors along the way: E-commerce Project Errors Here is a snippet of my index.js code: code snippet Any insight ...

Tips for achieving jQuery form submission with Ajax functionality

Currently in my Java application, I am submitting a form using JQuery. Below is the JSP code snippet: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> ...

What is the process for attaching an on-click event listener by utilizing an argument that is passed to a function in JavaScript?

These are the functions I have created: function type(message) { document.getElementById("body").innerHTML="<div id=\"textbox\" class=\"textbox\"></div><div id=\"oc\&q ...

What is the best way to show information entered into a textbox on a different webpage?

Looking for advice on how to collect data in a text box and display it on another page? I have included HTML code for both the announcement page (where the data is entered) and the archive page (where the data should be shown). Could someone guide me on ...

What is the correct way to run javascript on a DOM element when ng-show is triggered?

For those who prefer shorter explanations, there's a TLDR at the end. Otherwise, here's a detailed breakdown. I have a form that consists of multiple inputs organized into different "pages" using ng-show. What I aim to achieve is when ng-show r ...

Having trouble with your jQuery tag cloud?

I am encountering an issue with my website. I tried implementing a tag cloud feature, but it seems to be malfunctioning. ({ tags: [{ tag: 'asdasd', freq: '4' }] }) { tag: 'asdasdsadasd', freq: ...

Adjust the width of every column across numerous instances of ag-grid on a single webpage

I am facing an issue with Ag-grid tables on my webpage. I have multiple instances of Ag-grid table in a single page, but when I resize the browser window, the columns do not automatically adjust to the width of the table. We are using only one Ag-grid in ...

iOS devices experiencing issues with fixed positioning

Currently, I am in the process of implementing a few instances of , but I am encountering some issues with the CSS. When viewing the website on an iPad or iPhone, the calendar is positioned correctly as the container covers the window like a fixed position ...

Implementing a method to ensure both filters remain active with jquery

I am currently working on filtering a table based on the columns for department and location. Currently, these filters work individually but I am stuck on how to implement both filters simultaneously. I need assistance in figuring out how to filter all " ...

Do window.location.href and window.open interfere with each other?

I'm attempting to open a PDF in a new URL and redirect the user to the homepage at the same time. However, these two conditions in the "if" block are conflicting with each other. The page successfully redirects to the homepage, but the window.open() f ...

Experiencing Access-Control-Allow-Origin Issue with Behance API and Queryloader?

How fascinating! I've been experimenting with the Behance API to fetch data from my profile and create a sleek portfolio carousel. Recently, I encountered some issues after incorporating QueryLoader2 into my webpage: https://i.sstatic.net/k67mC.png ...

Organize and conceal identical columns in an Angular 4+ table

My goal is to organize the table by both name and first name. If there are any duplicate entries, I plan to keep just one line visible while adding an accordion feature to display the duplicates in a collapsed manner. Included below is the TS and HTML ...

Animating a div using a changing scope variable in AngularJS

As a newcomer to Angular, I am looking to add animation to a div element using ng-click within an ng-repeat loop. Here is what I have attempted: app.js var app = angular.module( 'app', [] ); app.controller('appController', function($ ...

Automatic Email Reply that Automatically populates the recipient field with the sender's information

I'm curious to know if it's possible to create a mailto link that automatically populates the TO: field with the email of the original sender, without including the email address in the link itself. For instance: "a href="mailto:ORIGINALSENDER? ...

Attempting to change the appearance of my jQuery arrow image when toggling the visibility of content

Here is a sample of my JQuery code: $(document).ready(function() { $(".neverseen img").click(function() { $(".neverseen p").slideToggle("slow"); return false; }); }); Below is the corresponding HTML: <div class="neverseen"> <h1> ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

Is there a solution for the noticeable delay in loading fonts on a web page?

I've encountered an issue in my React project where a Google font I'm using seems to briefly load as a different font before switching to the correct one. How can I prevent this from happening? This is how I'm loading the font in public/ind ...

Populate the containing div with an image element

I am looking to fill a parent div with an img, but I want the image to be a standalone img element inside the div, rather than setting it as a background property. To clarify, instead of this: div { background-image: url('someimg.jpg'); ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...