Friday, September 20, 2019

How to prevent click on the specified HTML element using CSS, JS or jQuery

Recently I have got a simple requirement of making specified HTML element non-clickable conditionally. I am free to choose how to implement this i.e. either by using CSS, JS, jQuery. Today I would be sharing how I have achieved this. It might be not the best or optimal solution but it worked for me. Let me know what could be another possible solution for this.

Since the requirement was to make some HTML element non-clickable conditionally, I have used both jQuery and CSS to achieve the complete requirement. But I have used CSS property pointer-events: none to prevent the click on the specified HTML element. The pointer-events property defines whether or not an element reacts to pointer events. Here, I used two of its values i.e.
auto : The element reacts to pointer events, like hover and click. This is default
none : The element does not react to pointer events
$('#topicMenu').children('li:not(.selectedTopic)').css("pointer-events","auto"); //making it again clickable
$('#topicMenu').children('li:not(.selectedTopic)').css("pointer-events","none"); //making it non-clickable

Later I came through one more method using jQuery in StackOverflow but haven't verified it if it really works:
$('selector').click(false); //If using jQuery versions 1.4.3+:
$('selector').click(function(){return false;}); //else 
Feel free to share any new way to make the specified HTML element non-clickable. Happy Learning!!

No comments:

Post a Comment