Akshay
Akshay

Reputation: 14378

Jquery click working only once

I am trying to draw lines between two points. I managed to do that but the problem is it only works once.The second time i click on a circle nothing's happening

This works only in modern browsers

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());
    }
})
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 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" />
    <circle cx="30" cy="30" r="30" />
    <circle cx="120" cy="120" r="30" />
    <circle cx="210" cy="120" r="30" />
    <circle cx="300" cy="120" r="30" />
    <circle cx="30" cy="120" r="30" />
    <circle cx="30" cy="210" r="30" />
    <circle cx="120" cy="210" r="30" />
    <circle cx="210" cy="210" r="30" />
    <circle cx="300" cy="210" r="30" />
    <circle cx="120" cy="300" r="30" />
    <circle cx="210" cy="300" r="30" />
    <circle cx="300" cy="300" r="30" />
    <circle cx="30" cy="300" r="30" />
</svg>

EDIT: This seems to work in snippet but not in the fiddle http://jsfiddle.net/akshay7/m2g6w80y/4/

Upvotes: 2

Views: 74

Answers (1)

Satpal
Satpal

Reputation: 133453

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

Since you are replacing content using

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

You need to use Event Delegation using .on() delegated-events approach.

i.e.

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

Example

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

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

DEMO

Upvotes: 4

Related Questions