How do I disable a link with javascript and css? - javascript

Do you know how to disable link for user only? I have
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">Banana</div>
So idea is that link /search/Banana is a valid link and I want to keep it for search indexing engines. However, I want when user click on link, the function searchoffertext_selected was called and nothing more happened.

To stop the link from taking its default action add return false; to the onclick event:
<div class="searchoffertext" onclick="searchoffertext_selected('Banana'); return false;">Banana</div>
It's probably a better idea to put the onclick directly on the <a>
But an even better approach would be to use unobtrusive JavaScript to attach an event to the link via a selector.
See also: Stackoverflow: When to use onclick in HTML?

Using jQuery:
$('#selector').click(function(e){
e.preventDefault();
});
VanilaJS:
<a onclick="return false;">

Try this?
js
document.querySelectorAll('.searchoffertext > a').onclick = function(e) {
e.preventDefault();
searchoffertext_selected(this.getAttribute("data-fruit"));
}
html
<div class="searchoffertext">
Banana
</div>

HTML
<div class="searchoffertext" onclick="searchoffertext_selected('Banana')">
Banana
</div>
CSS
Use pointer-events, but this is unsupported in versions of IE older than 11.
.searchoffertext > a {
pointer-events: none;
}
JavaScript
Prevent the default action from executing when the link is clicked:
var links = document.querySelectorAll('.searchoffertext > a'), i;
for(i = 0; i < links.length; i += 1) {
links[i].addEventListener('click', function(e) {
e.preventDefault();
}, false);
}

Related

html <a> link javascript function with parameter

I'm trying to pass one parameter (text variable) from a <a> tag. This is the code that I'm using:
<a onclick='javascript:Page_Change('Previous')' class='PageLink'>Previous</a>
Without the parameter 'Previous' is O.K and the function is working correctly. There is any possibility to pass the parameter value only using pure js?
If you want to do it inline you can do this:
<a onclick="javascript:Page_Change('Previous')" class='PageLink'>Previous</a>
But it's better to keep it seperate like this:
<a id="prev" class = "PageLink">Previous</a>
You may bind the event handler using the jQuery library
<script>
// jQuery
$('#prev').click(function() {
Page_Change('Previous')
});
</script>
or using standard JavaScript
<script>
// javascript
document.getElementById('prev').addEventListener('click', function() {
Page_Change('Previous')
}, false);
</script>
May I suggest this, where you can pass a number of links having different parameters.
<a data-param="Previous" class="PageLink">Previous</a>
<a data-param="Next" class="PageLink">Next</a>
var links = document.getElementsByClassName("PageLink");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function(e) {
Page_Change(e.target.getAttribute("data-param"))
}, false);
}

preventDefault doesn't work with external links?

So I have the following code:
JS
function overlay() {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
return true;
}
$("#close-link").click(function(event) {
event.preventDefault();
var targetUrl = $("#confirm").attr("href");
});
$("#confirm").click(function(event) {
event.preventDefault();
});
$("#go").click(function(event) {
event.preventDefault();
});
HTML
<div id="overlay">
<div id="dialog">
<h3 class="top-bar">Leaving so soon?</h3>
<span class="close-button-container">[X]</span><br /><br /><br />
Example text
<br />No, take me there anyway...
</div>
</div>
<!-- ... -->
Example Link
The Problem
I tried adding a link to another site. But I wanted to add a confirmation box once this link is clicked. The #close-link is used to close the dialog and the #confirm link as seen above should open it. The #go link is inside the dialog and if clicked brings the user to the location of the #confirm link. But something went wrong... Now when I click #confirm it opens the dialog for a second and directly sends me to its href. Shouldn't event.preventDefault fix this? If so, then why doesn't it?
Add an event to overlay(event). This function needs to prevent the click so it should have the e.preventDefault()
Example Link
function overlay(event) {
event.preventDefault();
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
var href = event.target.href
//If click button close
//Hidden div, no go
//If click button go
//window.location = href
}
Explanation
Your <a> has two events binded to it. One with #confirm and one with the inline onclick=. You should choose only one :)
So, a few things;
Remove all inline event handlers
When using jQuery, make the most of it and avoid writing vanilla javascript unless there is a reason to do so.
Do not use A for any other purpose than an actual link (The close button in your case). Use a button/other tags.
Take a look the below code and see if that's what you wanted.
$("#confirm, #close-link").click(overlay);
function overlay(evt) {
evt.preventDefault();
var el = $("#overlay");
el.css({"visibility": el.css("visibility") === "visible" && "hidden" || "visible"});
if ( this.tagName === 'A' ) {
el.find("a").attr("href", this.href);
}
}
#overlay {
height: 150px;
width: 200px;
background: green;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="overlay">
<div id="dialog">
<h3 class="top-bar">Leaving so soon?</h3>
<span class="close-button-container" id="close-link">[X]</span><br /><br /><br />
Example text
<br />No, take me there anyway...
</div>
</div>
<!-- ... -->
Example Link
If your code was called as part of an event listener callback, event.preventDefault() would work. But your code is running due to onclick which simply runs the function overlay() - attaching listeners to various elements (#close-link, #go, #confirm) using jQuery. After the listeners are attached, they start listening for events, which never come since the <a href="..."> changes the page.
Solution:
It is best to stop using on* attributes for all your codes. Take it out. Then use only event listeners for all your needs.
$('#confirm').on('click', function(event) {
event.preventDefault(); // this will work
// Do your toggle visibility and whatever else you need here.
});
There are other possible solutions that continue to use onclick calling a function, but I wouldn't recommend it.
Try attaching the click event to the #confirm element inside $(document).ready:
$(document).ready(function() {
$("#confirm").on("click", function(event) {
event.preventDefault();
});
});

Remove Div on link click

I am doing a code in which I want to delete a div when its inner link("Delete") is clicked. I know this question might be repeating and I have tried so many methods but not working. I dont know what's the problem.
Here is my HTML Rendering Code:
<div id="ViewRows">
<br>
<div class="ViewRow"> NOS: FA Comment: finance
<a class="deleteViewRow" href="#">Delete</a>
<br>
</div>
<div class="ViewRow">
NOS: TPA Comment: Assistance
<a class="deleteViewRow" href="#">Delete</a>
<br>
</div>
</div>
Here is my javascript Code for removal of that div.
$("a.deleteViewRow").live("click", function () {
$(this).parents("div.ViewRow:first").remove();
return false;
});
I also tried following javascript:
$("#ViewRows").on("click", "a.deleteViewRow", function () {
$(this).closest("div.ViewRow").andSelf().remove();
return false;
});
I have tried same code on another page. It is working but when I applied the same logic in another page. It's not working. I know you all are right but I dont know whats problem. In firebug it's not even going into the function.
This should work:
$("#ViewRows").on("click", "a.deleteViewRow", function (e) {
// prevent browser from following link
e.preventDefault();
// ".andSelf()" can be skipped - once the parent div is removed, the link gets removed as well
$(this).closest("div.ViewRow").remove();
});
this simple yet efficient code works fine: http://jsfiddle.net/L2CsH/
$("#ViewRows").on("click", "a.deleteViewRow", function () {
$(this).parent().remove();
});
you need to prevent default action of link. event.preventDefault()
$("#ViewRows").on("click", "a.deleteViewRow", function (e) {
e.preventDefault();
$(this).closest("div.ViewRow").remove(); //.andSelf() is not needed here.
//return false;
});
Demo : Remove Div JSFiddle

How to execute .click() code when previous click binding finishes

I am trying to use a Twitter Bootstrap button group with data-toggle="buttons-radio" in my site. Bootstrap markup as follows.
<div class="btn-group program-status" data-toggle="buttons-radio">
<button class="btn">All</button>
<button class="btn">Active</button>
<button class="btn">Planning</button>
<button class="btn">End of Life</button>
<button class="btn">Cancelled</button>
</div>
I need to redirect to the same page with query depending on the pressed button. I tried to use following jQuery code to achieve this.
<script>
var sParamStr = '';
function addToParamStr(str) {
sParamStr += str;
}
function redirectToUpdatedLocation() {
$('.program-status > .btn.active').each(function () {
addToParamStr( '?status=' + $(this).text());
});
console.log(sParamStr);
window.location.href = "program" + sParamStr;
}
$document.ready(function () {
$('.program-status > .btn').on('click', function (e) {
redirectToUpdatedLocation();
});
});
</script>
But the browser always redirects to {site}/program without the query string. By commenting out window.location.href = "program" + sParamStr; line, I managed to observe that second click onwards, sParamStr getting appended properly.
It seems that, my code tries to read the text of the pressed button before, .button('toggle') method form bootstrap.js finished. Code worked as intended when I changed function as follows.
$document.ready(function () {
$( '.program-status > .btn').on('click', function (e) {
$(this).addClass('active');
redirectToUpdatedLocation();
});
});
While this method works for me right now, I would like to know the proper way to achieve this. i.e How to execute my code after previous click binding finishes?
UPDATE:
I found this link in the Twitter Bootstrap forum. Seems it is a known issue.
https://github.com/twitter/bootstrap/issues/2380
I'm not sure what Bootstrap's .toggle is doing exactly, but it seems like it does some sort of animation that completes with the setting of the active class. You can try enqueing your code instead:
$( '.program-status > .btn').on('click', function (e){
$(this).queue(function (next) {
redirectToUpdatedLocation();
next();
});
});
For example, click the div as it is being toggled: http://jsfiddle.net/9HwYy/
It also seems a bit silly to me to update every href instead of just the one you clicked on since you are changing the window location anyway.
try
$('.program-status > .btn.active').each(function(i,v){
v = $(v);
addToParamStr( '?status=' + v.text());
});
since im not sure "this" is working in your case.

Calling a specific function alone in javascript or jquery

i have a piece of code like this.
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.
how to do that?
It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick
You can see that parameters it mentions an $event object. So your html will become:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
and then your javascript will become:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle: http://jsfiddle.net/rtCP3/32/
Instead calling functions there inline use jquery to solve this issue:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});
For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating
<div class="box" onclick="displayinfo(event)">
Then change js to:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
DEMO: http://jsfiddle.net/MvgTd/
whatever you are getting.stopPropagation();
in your case
$event.stopPropagation();

Categories