2

I have some HTML elements

<p class="accordion-header open" id="platform_0" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_1" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_2" onclick="validateScreens(this)">Platform 0</p>

I want to remove and restore the click event on this element. My JavaScript code is :

function validateScreens(domObj)
{   
  if(some condition)
  {  
    $(domObj).off("click"); // //remove click from  <p> whenever there is a click event
  } else {
    $(domObj).on("click",function() { return true; });// restores the click event      
  }
}

It is removing the click event successfully but not restoring it.How to do it.

2
  • what is the some condition? Commented Nov 27, 2016 at 2:23
  • Once the click event handler removed, how you can restore the same inside the click event which is never going to call once again as you removed it? Commented Nov 27, 2016 at 2:26

3 Answers 3

1
<p class="accordion-header open" id="platform_0" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_1" onclick="validateScreens(this)">Platform 0</p>
<p class="accordion-header open" id="platform_2" onclick="validateScreens(this)">Platform 0</p>
<script>
function validateScreens(domObj){   
       if(some condition){  
           $(domObj).on("click" , function( e ){ e.preventDefault(); }); 
     }else{
           $(domObj).on("click",function() {  return true; });
        }
}</script>

when event.preventDefault method is called the default action of the event will not be triggered.

Read More on : https://api.jquery.com/event.preventdefault/

Sign up to request clarification or add additional context in comments.

1 Comment

What's the default action for a <p>?
0

Why not trying different approach of having this check in the event handler itself

var allowClick = true;

function validateScreens(domObj) {
    if (some condition) {
        allowClick = true;
    } else {
        allowClick = false;
    }
}

$(domObj).on("click", function() {
    if (allowClick) {
        // Do click logic here
    }
});

Comments

0

put it inside same If condition. please try this one:

if(some condition)
  {   
     //remove click and restore it
    $(domObj).off("click").on("click",function() { return true; });
  } else {
    // anything else if false      
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.