Skip to content
Advertisement

Changing any element’s text into “TEXT-1” with one click and changing any element’s text into “TEXT-2” with doubleclick

If any element’s text is clicked once it is changed into “TEXT-1” otherwise if doublecliked into “TEXT-2”. So I have created a conditional with 2 different sentences according to the different output. In the present JS there is a problem with e which is not defined and I do not know how to fix it. Also I am not sure if the syntax of e.type === 'click' and later on e.type === 'dblclick' is correct.Thanks

if ( e.type === 'click')
{
    document.querySelector('ul').addEventListener('click', onClick)
    function onClick(e){
    let val;
    val = e.target.innerText = 'TEXT-1';
    

e.preventDefault();

    console.log(val)
}} else if (e.type === 'dblclick'){
    document.querySelector('ul').addEventListener('dblclick', onClick)
    function onClick(e){
    let val;
    val = e.target.innerText = 'TEXT-2';
            
        
e.preventDefault();
        
    console.log(val)
}}
            <ul>
              <li>
                List Item 1
              </li> 
              <li>
                List Item 2
              </li> 
              <li>
                List Item 3
              </li>
              </ul>

Advertisement

Answer

You could try add multiple event listeners on your items.. In this example there is an unordered list with 3 items

const items = document.querySelectorAll('li');

items.forEach((e)=>{
    e.addEventListener('click', ()=>{
  e.textContent = "text1"
  });
  
  
    e.addEventListener('dblclick', ()=>{
  e.textContent = "text2"
  });
})
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement