Home > database >  jquery spacing letters onclick function not working
jquery spacing letters onclick function not working

Time:07-17

without click

<a >

After click

<a >

Here after click link change to active play.so how to query on click if only single-item__cover active play is active only

my javascript

const $featured =$('a.single-item__cover.active.play');

$featured.on('change', function() {
    console.log('working fine');




    
});

CodePudding user response:

That because the event created before the elemen class exist.

for dynamic element/attribute you can attach the event to the body, but it will make the event double.

$('a.single-item__cover').on('click', (e)=>{
  e.preventDefault();
  $(e.target).addClass('active play');
  console.log('play');
})

$('body').on('click', 'a.single-item__cover.active.play', (e)=>{
  e.preventDefault();
  $(e.target).removeClass('active play');
  console.log('stop');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="" >play</a>

a better way is to use toggle strategy

$('a.single-item__cover').on('click', (e) => {
  let a = $(e.target);
  e.preventDefault();
  a.toggleClass('active play');
  if ((a).hasClass('play')) {
    a.text('Stop')
  } else {
    a.text('Play')
  }
})
.active.play {background: yellow;padding: 5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="" >Play</a>

CodePudding user response:

Here is a vanilla JavaScript snippet demonstrating how you can change the classes of some input elements (checkboxes before c, d, e) affecting their status being watched by an .addEventListener("change"...) listener. The key point and difference to OP's code is, that I add the listener to the document.body but limit the action to those "changed" elements that have at least the .active class set. You can make it more strict by checking both classes with an && condition, like

if (ev.target.classList.contains("active") && ev.target.classList.contains("play"))

const ctoe=[...document.querySelectorAll("input")].slice(2,5);
document.querySelector("button").onclick=()=>ctoe.forEach(e=>{
 e.classList.toggle("active");
 e.classList.toggle("play")
})
document.body.addEventListener("change",ev=>{
 if (ev.target.classList.contains("active"))
  console.log(ev.target.nextSibling.textContent " changed.")
})
<input type="checkbox" > a active<br>
<input type="checkbox" > b<br>
<input type="checkbox" > c *<br>
<input type="checkbox" > d *<br>
<input type="checkbox" > e *<br>
<input type="checkbox" > g<br>
<button>toggle c-e active</button>
* can be active or not, controlled by button.

  • Related