Reputation: 1521
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.
Upvotes: 2
Views: 320
Reputation: 1725
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
}
Upvotes: 0
Reputation: 7068
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
}
});
Upvotes: 0
Reputation: 758
<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/
Upvotes: 1