Preventing href in <a></a> from executing via Javascript - javascript

So I have this following code in my HTML:
<li class="" id="toolbar_section"><a id="toolbar_section_child" href="#foobar" onclick="return toolbarSetSection(this);" data-toggle="checkpoint">foobar</a></li>
And written in my Javascript is:
<script type="text/javascript">
function toolbarSetSection(event){
//some logic which leads to
return false;
};
</script>
However, the href still executes... I have checked many similar topics with answers like event.preventDefault(); but they don't help me either.

In your HTML you should change onclick="return toolbarSetSection(this);" to onclick="toolbarSetSection(event);", and then have event.preventDefault(); in your javascript function.
Your full code would be:
<li class="" id="toolbar_section"><a id="toolbar_section_child" href="#foobar" onclick="toolbarSetSection(event);" data-toggle="checkpoint">foobar</a></li>
and
function toolbarSetSection(event) {
event.preventDefault();
return false;
};

return false should usually work, but maybe there is an error in your toolbarSetSection function.
Calling event.preventDefault() should usually work, too. However in your case you expect the function to be called with event as first parameter, while your HTML code calls onclick="return toolbarSetSection(this);" with the link object as first parameter. Maybe you wanted to call toolbarSetSection(event); instead.

HTML
<ul>
<li class="" id="toolbar_section2"><a id="toolbar_section_child" href="#" onclick="toolbarSetSection()" data-toggle="checkpoint">foobar</a></li>
</ul>
js
function toolbarSetSection()
{
alert('started');
event.preventDefault();
alert('weee');
}
jsfiddle so you cannot say it is not working :) : https://jsfiddle.net/rgoopw18/1/

a better way to get the expected behavior without adding onclick on the tag
<script>
document.getElementById('toolbar_section_child').on('click', function(e){
e.preventDefault();
})
</script>
Assuming you have a unique id for the a tag.
EDIT
for dynamically created elements use event delegation
document.addEventListener('click',function(e){
/*
if(e.target && e.target.id == 'toolbar_section_child'){
e.preventDefault();
}
*/
// using a common class name
if(e.target && e.target.className.split(" ").indexOf("toolbar_section_child") != -1){
e.preventDefault();
}
})

Related

Multiple onclicks on the same div

I am trying to add a second onclick function to my element but so far without success, tried with different separators, same quotations and such but it does not work yet.
This is the code :
<a title="course" onclick="if(document.getElementById('spoiler') .style.display=='none') {document.getElementById('spoiler') .style.display=''}else{document.getElementById('spoiler') .style.display='none'};" onclick="if(document.getElementById('nav-res') .style.display=='block') {document.getElementById('nav-res') .style.display='none'};">Course</a>
Can anyone point out what I am doing wrong ? Much appreciated
I encourage you to try using event listeners:
<a href='#' id='mytag'>
and then:
<script>
document.getElementById('mytag').addEventListener("click", function(){
alert(1)
}, false);
document.getElementById('mytag').addEventListener("click", function(){
alert(2)
}, false);
</script>
or with jquery:
<script>
$('#mytag').click(function(){ alert(1) })
$('#mytag').click(function(){ alert(2) })
</script>
You cannot add multiple onclick statements.
You need to add a semicolon ( ; ) between the commands.
click me
//---------------------------------------------^---------------------------^
However, I would not do it the way you are doing it.
I would make a separate function that does whatever you are trying to do.
It's not good practice to put everything in the html (inline).
I would do it like this:
<a id="" onclick="clickme()">
<script>
function clickme() {
// action 1
if( document.getElementById('spoiler').style.display=='none' ){
document.getElementById('spoiler').style.display='';
}
else{
document.getElementById('spoiler').style.display='none';
};
// action 2
if( document.getElementById('nav-res').style.display=='block' ){
document.getElementById('nav-res') .style.display='none';
}
}
</script>

How to stop javascript onclick event

I have external link which render image with javascript onclick event.
I need to stop this click event.How can i do this ?
For example:
Html is render by external script:
<div class="demo-link">
<img alt="" onclick="verifylock();" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>
I have tried this with jquery but not get any luck:
$(".demo-link > img").click(function(e){
e.preventDefault();
});
You can remove the onclick value when dom is ready:
$('.demo-link > img').attr('onclick','').unbind('click');
Working Demo
You can always return false from the onClick event handler, call preventDefault, stopImmediatePropagation or other methods, but it would be no use here since HTMLs onclick gets invoked BEFORE jQuery onclick. If you do not want to simply remove the 'onclick' from HTML, you can change it programmatically (and even store it with jquery data() method for future use if needed).
$(".demo-link > img").each(function(e) {
$(this).onclick = function() { // overriding the onclick
return false;
}
});
A working snippet below:
function defaultOnClick() {
alert('Default event handler invoked!');
}
$('.clickable').each(function() {
$(this).data('onClickBackup', this.onclick);
this.onclick = function(event) {
alert('Overriden onclick');
return false;
// if you need to ever call the original onclick, then call below
// $(this).data('onClickBackup').call(this, event || window.event);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="clickable" onclick="defaultOnClick()">Click me!</div>
$(".demo-link > img").click(function(e){
return false;
});
You are writing event on click and calling a function using onclick in img tag. So remove onclick from img tag like.
<img alt="" src="https://example.com" style="cursor:pointer;cursor:hand">
if you want to call a function verifylock() call it from handler for click
Try your own code with return false;
<img alt="" onclick="verifylock(); return false;" src="https://example.com" style="cursor:pointer;cursor:hand">
</div>

dynamically add/remove input type file (browser field)

I have a input type file field and there is a label near this like "Add more",this is a hyper link. While clicking on this hyper link it should create another input type file field. Once it is created an another input type file field there should be link like "Remove", clicking on this link will remove the corresponding file field only.
Note that there is no limit of adding this file fields, but in worst case I will upto 10 file fields maximun. I meant to say there should be no condition to check whether it reached the maximum limit.
You can see my code here.http://jsfiddle.net/inDiscover/6hVkw/
HTML
<table>
<tr id="bkup_doc_rw">
<td align="right"><label class="letter_font" for="bkup_doc_proof">Document :</label></td>
<td> <input type="file" name="bkup_doc_proof" id="bkup_doc_proof" required/> <a class="letter_font" style="text-decoration:none;cursor:pointer;" href="#" id="addNew">Add more </a>
</td>
</tr>
</table>
JQUERY
var fle_cnt = 1;
$('#addNew').click(function() {
fle_cnt++;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#bkup_doc_rw').after('<tr><td> </td><td>
<input type="file" name="bkup_doc_proof" id="bkup_doc_proof_'+fle_cnt+'"> <a class="letter_font" style="text-decoration: none;cursor: pointer;" href="#" id="remNew">Remove</a></td></tr>');
return false;
});
$(document).on('click', '#remNew', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#remNew').parents('tr').remove();
return false;
});
Here issue is when I tried to clike on "Remove" label it is not removing the corresponding file field instead it is removing randomly. I know this issue is happening because I am not using unique ID (file_cnt) while deleting a filed.
Can any one help me to modify my code in a better way to achieve this.
Try this:
var fle_cnt = 1;
$('#addNew').click(function (event) {
fle_cnt++;
event.preventDefault();
$('#bkup_doc_rw').after('<tr><td> </td><td><input type="file" name="bkup_doc_proof" id="bkup_doc_proof_' + fle_cnt + '"><a class="letter_font remNew" style="text-decoration: none;cursor: pointer;" href="#">Remove</a></td></tr>');
});
$(document).on('click', '.remNew', function (event) {
event.preventDefault();
$(this).closest('tr').remove();
});
changes:
in the #addNew click pass the event in the callback.
change the id attribute to class instead.
instead of id selector change to the class selector .remNew.
instead of $('#remNew') place the context selector as $(this).
pass the event in the callback of .remNew's click event
You don't need to use return false; as you are already using event.preventDefault(); and it would work if you pass the event in the callback as mentioned above.
and instead of .parents() use .closest() to traverse up.
Demo # updated fiddle.
htry this:
$(document).on('click', 'a.letter_font', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$(this).parents('tr').remove();
return false;
});
inside the click event use $(this). this way you can manage the exact object which triggered the event.
#remNew That why !
IDs are mean to be unique.
$('#remNew').parents('tr').remove();
to
$(this).parents('tr').remove();
HTML pages must have the ID's unique. Make the remNew a class and you're fine:
JSFiddle
var fle_cnt = 1;
$('#addNew').click(function() {
fle_cnt++;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#bkup_doc_rw').after('<tr><td> </td><td> <input type="file" name="bkup_doc_proof" id="bkup_doc_proof_'+fle_cnt+'" /> <a class="letter_font remNew" style="text-decoration: none;cursor: pointer;" href="#" >Remove</a></td></tr>');
return false;
});
$(document).on('click', '.remNew', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$(this).closest("tr").remove();
return false;
});
You were using id = "remNew", should never use multiple id's - they are used specially to create unique identification,
for DOM elements with similar property we always use classes - so i replaced id with class = "remNew"
on click on some elements we able to detect it using this instance , and the use jquery closest to delete specific tr tag
make remNew as class, you can try this way too
`http://jsfiddle.net/MRqN4/`

javascript toggle visibility and add function preventDefault

i´m trying to display popup-divs within a site and it works quite well, except for one thing –
i want to prevent the Default behavior of refreshing the site. I´m new to javascript and i honestly don´t know how to add the function (i already found the right one, i think...).
<script type="text/javascript">
function toggleVisibility(selectedPopup) {
var popvar = document.getElementsByClassName('popup');
for(var i=0; i<popvar.length; i++) {
if(popvar[i].id == selectedPopup) {
popvar[i].style.visibility = 'visible';
} else {
popvar[i].style.visibility = 'hidden';
}
}
}
It works like i wanted it to work – it displays the selected DIV, hides the other and vice versa.
Still, i want to prevent the site from jumping to the top. So i added this snippet:
$(function() {
$("#").click(function(event){
event.preventDefault()
});
});
The responding html is this:
<a href="#" onclick="toggleVisibility('pop01');">
and this
<div id="pop01" class="popup">
<img src="assets/img/01/01_02_pop_01.png"></img>
</div>
How can i include the second javascript snippet into the first one?
Many thanks in advance...
You should just be able to pass event into your function.
The HTML
<a href="#" onclick="toggleVisibility(event, 'pop01');">
The Javascript (partial)
function toggleVisibility(event, selectedPopup) {
event.preventDefault();
var popvar = document.getElementsByClassName('popup');
// etc...
}
I believe that should do it!
JSFiddle Example: http://jsfiddle.net/c4LXf/
As an alternative you can just remove the # and replace with javascript:;
<a href="javascript:;" onclick="toggleVisibility('pop01');">
Or remove the onclick and just use the href:
<a href="javascript:toggleVisibility('pop01');">
Instead of
$(function() {
$("#").click(function(event){
event.preventDefault()
});
try
$(function() {
$("#").click(function(event){
return false;
});
You can just use following:
<a href="#" onclick="return toggleVisibility('pop01');">
If you add a return false in your function:
function toggleVisibility(selectedPopup) {
// your code ...
return false;
}
Or, Change your link like:
<a href="javascript:toggleVisibility('pop01');">

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

Categories

Resources