atho
atho

Reputation: 133

Change element id and behaviour on click

I need to make a button that changes its id on click, and its name. It changes only when I click the first time on "Start!". After that it is not working and I don't know why.

$("#start").click(function(){
  $(this).attr("id", "stop");
  $(this).html("Stop!");
});

$("#stop").click(function(){
  $(this).attr("id", "start");
  $(this).html("Start!");
});

Upvotes: 0

Views: 151

Answers (2)

mplungjan
mplungjan

Reputation: 178421

Changing ID is not a good idea.

have a button and toggle the class and content

$("#toggle").on("click",function(){
  $(this).toggleClass("stop");
  $(this).html($(this).is(".stop")?"Stop":"Start"); // if ($(this).is(".stop")) {} else {} 
});
.stop { background-color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="toggle">Start</button>

Upvotes: 4

Magus
Magus

Reputation: 15124

The $('#stop') selector can't works because you have no html element with the id stop when you run it. So you have 2 choices : Use only one listener or use the delegation system of jQuery.

One listener :

$('#start').click(function() {
    var $this = $(this),
        id = $this.attr('id');

    if (id == 'start') {
        $this.attr('id', 'stop');
        $this.html('Stop!');
    } else {
        $this.attr('id', 'start');
        $this.html('Start!');
    }
});

Delegation system :

$(document.body).on('click', "#start", function(){
  $(this).attr("id", "stop");
  $(this).html("Stop!");
});

$(document.body).on('click', "#stop", function(){
  $(this).attr("id", "start");
  $(this).html("Start!");
});

Anyway, mplungjan is right. Changing the ID is not a good idea. You should use a CSS class for that.

Upvotes: 2

Related Questions