switch contenteditable attr

Viewed 20

Why does the line obj.attr(b, 'false').blur(); not work? What is wrong here?

$('#btnren').on('click', function() {
  let obj = $('#cptitlea');
  let b = 'contenteditable';
  if (obj.attr(b, 'false')) {
    obj.attr(b, 'true').focus(); // this works
  } else {
    obj.attr(b, 'false').blur(); // doesn't work
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>

1 Answers

The issue is because you're using the setter of attr() in the if statement. This means your if is actually saying 'if (jQuery object exists)', which is always true.

To fix this, use the getter of attr() to retrieve the value and use it in the if statement. Note that you can simplify the logic by providing a function to attr() which returns the new value to be set, based on the current one. Try this:

$('#btnren').on('click', function() {
  let $el = $('#cptitlea');
  let b = 'contenteditable';
  
  $el.attr(b, function(i, v) {
    return v === 'true' ? false : true;
  }).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='cptitlea'>323</div>
<br>
<button id='btnren'>CLICK</button>

Related