How to disable ALL links' default click behaviour using jQuery? - javascript

EDIT: The original error was a typo. I will rewrite it so it stays useful to the community.
How to disable all links with a certain class (e.g. ".disabled") from linking without adding a handler to each element?
The advantages of this approach is that it would work with every link (or element) with this class no matter if they were added dinamically or changed their classes during the life cycle of the webpage.
It is acceptable (for this use case) if the solution stops the "click" event from bubbling.
It is not acceptable (for this use case) to remove the href attribute, it might be "not disabled" later.

DEMO with the debugging and listing all delegated events.
You can use jQuery's .on() method on the container, and you wont have the bulk of hundreds of click events.
HTML:-
<div id="container"> // #container has the event handler assigned
<a>content</a>
Disabled
Not disabled
<a>content</a>
</div>
jQuery
// Whenever <a> elements that descend from #container get
// clicked the click event handler will fire.
$('#container').on( 'click','.disabled', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});

You will have to attach an event to each element (this will do it):
$(".disabled").click(function(e){
e.stopPropagation();
e.preventDefault();
});

Apply following class to all a elements:
.not-active{
pointer-events: none;
cursor: not-allowed;
}
$('a').addClass('not-active');

<div class="body">
Enabled
Disabled
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(".body").on('click','a',function(e){
if ($(this).is('.disabled')) {
e.preventDefault();
e.stopPropagation();
alert("Click disabled");
}
});
</script>
This works for me.

You can disable for redirect on linked url by this code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
google
<br />
Facebook
</body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
jQuery('body').click(function () {return false;});
</script>
</html>

<div id="container"> // #container has the event handler assigned
<a>content</a>
Disabled
Not disabled
<a>content</a>
</div>
$(document).ready(function(){
$('#container').on( 'click','.disabled', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
});

Simply replace the href links with void reference:
$('.disabled').each(function(i) {
if ($(this).attr('href')) $(this).attr('href', 'javascript:void(0);');
});
As a followup measure, in case you still need the actual links, you could save them to the object's data, then change them!
$('.disabled').each(function(i) {
var href = $(this).attr('href');
if (href) {
$(this).data('href', href)
.attr('href', 'javascript:void(0);');
}
});
Example
$('.disabled').each(function(i) {
var href = $(this).attr('href');
if (href) {
$(this).data('href', href)
.attr('href', 'javascript:void(0);');
}
});
setTimeout(function() {
$('.disabled').each(function(i) {
var href = $(this).attr('href');
if (href) {
var href = $(this).data('href');
console.log(href)
$(this).after($('<i />', { html: ' - My old Link was: <b>' + href + '<b />' }).fadeIn());
}
});
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
bob<br />
<p class="disabled">ron</p><br />
jane<br />
<h3 class="disabled">sally</h3><br />
trump<br />

Related

Hide/Show div on click and scroll

I want to create a search form which is hidden and when we click the search icon that form appears and when user click away or scrolls the search form hides.
You have to use .onclick event in js and change display and visibility property in a function. For example:
document.getElementById("searchIcon").onclick = searchFunction
function searchFunction(){
const search = document.getElementById("searchForm");
search.style.display = "block";
search.style.visibility = "visible";
}
Of course, by default it should be hidden. But display: none is not nesseccary, depends on your website.
Try this:
Whenever you click on the image, "This is part of the div" appears in Red.
Basically, you use Javascript to set/remove the hidden Attribute every time the user clicks the <img> item. Additionally, you change the <img>'s onclick Attribute to the opposite function(show_div()==>hide_div();hide_div()==>show_div()):
//see html on where to put this
show_div=function(){//Executed when the div ISN'T shown and the user clicks on the <img> tag
document.getElementById("search_div").removeAttribute("hidden");
document.getElementById("search_icon").setAttribute("onclick","hide_div()");}
hide_div=function(){//Executed when the div ISN'T shown and the user clicks on the <img> tag
document.getElementById("search_div").setAttribute("hidden","true");
document.getElementById("search_icon").setAttribute("onclick","show_div()");}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Example Page</title>
</head>
<body>
<img height="32" width="32" src="https://cdn-icons-png.flaticon.com/512/3917/3917754.png" onclick="show_div()" id="search_icon">
<div id="search_div" hidden="true">
<font size=7 color="Red">This is part of the div</font>
</div>
<script type="text/javascript">//put the Javascript part here when copy-pasting this code
</script>
</body>
</html>
You might want to take a look at the "hidden" attribute and the "click" event.
i am using addEventListener to get if any click is happened you can use any section of the on the place of document to make it work for that particular section. i.e: header
and then i am using classList.toggle to add and remove a particular class from the search input box.
you can add CSS as per your need.
var searchbox=document.querySelector("#search-bar");
var searchIcon=document.querySelector(".search-icon");
document.addEventListener("click",searchBar);
function searchBar(){
searchbox.classList.toggle("search-bar");
}
.search-bar{
display:none;
}
<div>
<input class="search-bar" id="search-bar" type="text" placeholder="search...">
<i class="search-icon">🔍 </i></div>
This jquery function worked for me
'
$(document).ready(function(){
$(window).scroll(function(){
$("#search").fadeOut();
});
$("body").click(function(){
$("#search").fadeOut();
});
$("#btn").click(function(event){
event.stopPropagation();
$("#search").fadeToggle();
});
}); '
with this function when user scrolls the page the search bar will hide
below is a javascript version
document.addEventListener("DOMContentLoaded", function() {
window.addEventListener("scroll", function() {
document.getElementById("search").style.display = "none";
});
document.body.addEventListener("click", function() {
document.getElementById("search").style.display = "none";
});
document.getElementById("btn").addEventListener("click", function(event) {
event.stopPropagation();
var search = document.getElementById("search");
if (search.style.display === "none") {
search.style.display = "block";
} else {
search.style.display = "none";
}
});
});

jQuery toggleClass only toggles once

I have a div which i am trying to toggle its class from one to another. I am able to toggle it only once but it will not return to the original class. I looked around for possible answers and looked into the propogation function, however i am unsure this is the correct use?
<body>
<div id="wrapBreather">
<div id="counter" class="cInact">
<!--<canvas id="timerAnimation"></canvas>-->
</div>
</div>
<br />
<button id="startStopCount" class="HomeButton" >Start</button>
<script>
$(startStopCount).click(function(e){
e.stopPropagation();
$('.cInact').toggleClass('cDown cInact');
});
$('html').click(function () {
$('#counter').removeClass('cDown');
});
</script>
</body>
You are getting the element via $('.cInact'). However, when you toggle the class .cInact, you can no longer get that element by $('.cInact') (it doesn't have that class anymore).
You can either do a selection with $('#counter') (getting the ID instead of the class, because you aren't toggling the ID) or assign the element reference to a variable:
var myAwesomeCounter = $('.cInact');
// Then use
myAwesomeCounter.toggleClass('cDown cInact');
Well, you're selecting the class 'cInact' and then toggling it's class.
i.e- removing it.
Wen you're trying to select the element again with the same selector: classname == cInact it's no longer true for that element. so you select nothing, and nothing happens.
To fix this, try using a different selector- e.g- id, like so-
$('#counter').toggleClass('cDown cInact');
The selector $(startStopCount) is wrong. It should be $("#startStopCount")
$('#startStopCount').click(function(e){
e.stopPropagation();
$('.cInact').toggleClass('cDown');
});
$('html').click(function () {
$('#counter').removeClass('cDown');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapBreather">
<div id="counter" class="cInact">
<!--<canvas id="timerAnimation"></canvas>-->
</div>
</div>
<br />
<button id="startStopCount" class="HomeButton" >Start</button>
</body>
$('#startStopCount').click(function(e){
e.stopPropagation();
$('#counter').toggleClass('cDown cInact');
});
$('html').click(function () {
$('#counter').removeClass('cDown');
});
Better perhaps:
$('#startStopCount').click(function(e){
e.stopPropagation();
$('#counter').toggleClass('cDown cInact');
});
$('body').click(function () {
$('#counter').removeClass('cDown');
});

.load() not working on ul li click

here is my code
$(document).ready(function(){
$("#work").click(function(){
$("#container").load("about/work.html");
});
$("#profile").click(function(){
$("#container").load("profile.html");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a id="work" href="">work</a></li>
<li><a id="profile" href="">profile</a></li>
</ul>
<div id="container"></div>
when i click on work or profile requested page just flashes in container div and sometime stays in but if i run same script on button click it loads page without any problem. How can i make it work with li ?
Add event.preventDefault
$(document).ready(function(){
$("#work").click(function(event){
event.preventDefault(); //changed here
$("#container").load("about/work.html");
});
$("#profile").click(function(event){
event.preventDefault(); //changed here
$("#container").load("profile.html");
});
});
There are 2 things to be changed here.
1) Try not leaving your href value empty. If you do then the browser will redirect to the same page. Give it a value # if possible href="#"
2) There is preventDefault() function missing from your <a> click event
$(document).ready(function(){
$("#work").click(function(e){
e.preventDefault();
$("#container").load("about/work.html");
});
$("#profile").click(function(e){
e.preventDefault();
$("#container").load("profile.html");
});
});
try to on click
$(document).ready( function() {
$("#work").on("click", function() {
$("#container").load("about/work.html");
});
});

loop through all anchor tags of html page using jquery?

i want to refrence all anchore tags on page that have
<body>
<h1>not me</h1>
<h1>not me also </h1>
<h2>me also as i am H2 </h2>
<h3>not me also </h3>
<h2>me also as i am H2 </h2>
<button onclick="score2Dmatrix();" id="btn" ></button>
h2 tag as their parent using jquery , for that i have to pass through each anchor tag that have parent h2 and then add attribute
onclick="callme();";
i am using that code onclick
<script>
function callme() {
$("h2 a").each(function () {
$(this).attr("onclick", "score2Dmatrix();");
});
};
</script>
but no effort
link to fiddle is this jsfiddle
thanks for that tobby answers is right
selector(h2 + a)...
Please see: https://jsbin.com/towejoqudu/edit?html,js,console,output
I have added text into your anchors so you can actually click them.
$('h2').find('a').on('click', callme);
You can avoid all of the unnecessary traversal by binding to the body once (event delegation), like so:
$('body').on('click', 'a', function(){
var $clicked = $(this);
if($clicked.closest('h2').length){
callme();
}
});

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});

Categories

Resources