javascriptonclick

How can I conditionaly remove the default behavior of an anchor (a) tag added by insertAdjacentHTML


I am trying to add an anchor tag that should redirect the user to another page only if a condition is met (here if array.length<3). I have followed Iananswer of this SO question, but in my case I am inserting the a tag using a function and insertAdjacentHTML as described below. The other thing is that I need to pass a parameter (the array itself) to check its length. I could not get it to work the first snippet is form Ian answer which works perfectly. The second is another way of doing it using a div and the third one is the one I am breaking my head overbut can't find the proper way of writing it.

<a onclick='return handleClick()' href="https://www.example.com">click</a>

<div class="check-div" id="check-div" style="cursor:pointer;">click</div>

<div class="elem1"> I am elem1</div>
//snippet 1

let checkDiv = document.querySelector('.check-div')

let array = ['1', '2', '3']

const handleClick = () =>{
    // return false
    if(array.length <= 3){
        location.href = 'https://www.example.com'
    }else{
        alert('Maximum 3 items to be compared')
        return false
    }
}

//snippet 2

checkDiv.addEventListener('click', ()=>{
    if(array.length <= 3){
        location.href = 'https://www.example.com'
    }else{
        alert('Maximum 3 items to be compared')
    }

})

//snippet 3

function addElements(elem){
    let elem1 = document.querySelector('.elem1')
    elem1.insertAdjacentHTML('beforeend',`<a class='atag' onclick="ps_block_user(elem)" href="./compare-products/" target="_blank">cliquez pour comparer</a>`)
}

function ps_block_user(elem){
    if(elem.length>3){
        alert('Un maximum de 3 produits à comparer est possible!')
        return false
    }
}

addElements(array)

I also tried using an click event listener as below but here still we can't prevent redirection as oppposed to the first snippet..

let atag = document.querySelector('.atag')
atag.addEventListener('click', ()=>{
    if(array.length>2){
        // return false
        alert('Un maximum de 2 produits à comparer est possible!')
        return false
    }
})

Solution

  • onclick attributes are executed in the global scope, so they can't refer to local variables in the function.

    Instead of adding HTML, create the element directly and use addEventListener(). Then you can refer to the variable.

    function addElements(elem){
        let elem1 = document.querySelector('.elem1');
        let anchor = document.createElement('a');
        anchor.class = 'atag';
        anchor.href = './compare-products';
        anchor.target = '_blank';
        anchor.innerText = 'cliquez pour comparer';
        anchor.addEventListener('click', function(e) {
          ps_block_user(elem, e);
        });
        elem1.appendChild(anchor);
    }
    
    function ps_block_user(elem, event){
        if(elem.length>3){
            alert('Un maximum de 3 produits à comparer est possible!')
            event.preventDefault();
        }
    }