John
John

Reputation: 425

Disable click html elements jQuery

So for those who can't wait fiddle

I am developing something like this and I am just new in the world of jQuery :) My problem is how do I enable and disable the clicks of the <i> element when I click the disable and enable buttons below :) Thank you so much for your answers. I would really appreciate it.

Preview Code:

HTML

<ul class="controls">
    <li><i class="fa fa-pencil" data="a1"></i></li>
    <li><i class="fa fa-trash" data="a2"></i></li>
    <li><i class="fa fa-align-justify" data="a3"></i></li>
</ul>

<span class="disable">Disable</span>
<span class="enable">Enable</span>

CSS

.controls{
    list-style: none;
}

.controls li{
    display: inline-block;
    margin: 0px 5px;
}

.controls li i{
    cursor: pointer;
}

.disable,
.enable{
    margin: 10px;
    background: #000;
    color: #fff;
    padding: 3px 5px;
    cursor: pointer;
}

JS

$(document).ready(function(){
    $('.controls li i').click(function(){
        alert($(this).attr("data"));
    });
});

Upvotes: 0

Views: 1351

Answers (2)

ClementBresson
ClementBresson

Reputation: 55

You can do it like this :

$('.disable').click(function(){
    $('.controls li i').removeClass('clickable');
});

$('.enable').click(function(){
    $('.controls li i').addClass('clickable');
});

$('.clickable').click(function(){
    //actions you want
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Use .off() to remove the handler

$(document).ready(function() {
  function handler() {
    alert($(this).attr("data"));
  };
  $('.controls li i').click(handler);

  $('.disable').click(function() {
    $('.controls li i').off('click', handler);
  })
  $('.enable').click(function() {
    //off is used here so that duplicate handler registration won't happen if you click on enable twice
    $('.controls li i').off('click', handler).click(handler);
  })
});
.controls {
  list-style: none;
}
.controls li {
  display: inline-block;
  margin: 0px 5px;
}
.controls li i {
  cursor: pointer;
}
.disable,
.enable {
  margin: 10px;
  background: #000;
  color: #fff;
  padding: 3px 5px;
  cursor: pointer;
}
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="controls">
  <li><i class="fa fa-pencil" data="a1"></i></li>
  <li><i class="fa fa-trash" data="a2"></i></li>
  <li><i class="fa fa-align-justify" data="a3"></i></li>
</ul>

<span class="disable">Disable</span>
<span class="enable">Enable</span>

Upvotes: 4

Related Questions