javascript toggle visibility and add function preventDefault - javascript

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');">

Related

disable href link if javscript call return false

I have following code, but it doesnt work
<a href="Order-addCopy?id=15658">
<img src="img/add.png" onclick="copyOrderPopupMsg()">
</a>
function copyOrderPopupMsg() {
if (confirm("open the following link?")) {
return true;
} else {
return false;
}
}
How can I disable the href link if the user click "cancel" on the popup window?
To cancel navigation using that style of code you have to return from the onclick function.
You are returning from copyOrderPopupMsg but you don't do anything with the result.
You also have to handle the event on the link not the image inside the link.
Note, also that confirm returns a boolean, so wrapping it in an if that generates a boolean is pointless.
A link with no text content is also highly inaccessible, don't forget the alt attribute
function copyOrderPopupMsg() {
return confirm("open the following link?")
}
<a href="Order-addCopy?id=15658" onclick="return copyOrderPopupMsg()">
<img src="img/add.png" alt="Add">
</a>
Modern code also avoids onclick attributes as they have numerous issues (including lack of separation of concerns and weird scoping issues) so I recommend using addEventListener and making use of the event object.
function copyOrderPopupMsg(event) {
if (!confirm("open the following link?")) event.preventDefault();
}
document.querySelector('a').addEventListener('click', copyOrderPopupMsg);
<a href="Order-addCopy?id=15658">
<img src="img/add.png" alt="Add">
</a>
I simple solution
<a href="Order-addCopy?id=15658">
<img src="img/add.png" onclick="return copyOrderPopupMsg()">
</a>
Just add the return in onclick.
You need to remove the link completely.
<img src="img/add.png" onclick="copyOrderPopupMsg()" data-href="Order-addCopy?id=15658">
function copyOrderPopupMsg(event) {
if (confirm("open the following link?")) {
window.location = event.target.dataset.href;
}
}
Make sure you have a full URL. The current one is not valid for this operation.
If you want to use a relative path, you can create a hidden link and click it by function.
<a class="hidden click-when-confirmed" href="Order-addCopy?id=15658"></a>
function copyOrderPopupMsg(event) {
if (confirm("open the following link?")) {
document.quertSelector('.click-when-confirmed').click();
}
}
I think preventDefault would be the best in your case:
function onclickA(e) {
if (!confirm('open the following link?')) {
e.preventDefault();
}
}
<a href="Order-addCopy?id=15658" onclick="onclickA(event)">
<img src="https://upload.wikimedia.org/wikipedia/commons/5/50/Yes_Check_Circle.svg" />
</a>
try this: remove anchor tag and change to this
function copyOrderPopupMsg() {
if (confirm("open the following link?")) {
document.location.href="Order-addCopy?id=15658";
} else {
return false;
}
}

Preventing href in <a></a> from executing via 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();
}
})

Variable refuses to be modified

So I have this code:
<script type="text/javascript">
function ExitPop() {
if(PreventExitPop != false) {
return "TEXT";
}
}
window.onbeforeunload = ExitPop;
</script>
as one could imagine, it asks the user if they're sure they'd like to leave.
I want to make it so that when they click on certain links, this code is disabled. How do I do this? I've tried setting PreventExitPop to false when the link is called, but that yielded no results. Lastly, I did the 4 spaces indent to make the above code indent like code, but it doesn't seem to work.
Assuming the first call changes the variable PreventExitPop to false, what am I doing wrong here:
<a href="http://www.mtrck.net/offer/79947|11640?data1=Track1&data2=Track2">
<img src="newpop1.jpg" alt="" width="532" height="570" onClick= "changeToFalse(false); MM_goToURL('parent',''http://www.mtrck.net/offer/79947|11640?data1=Track1&data2=Track2');return document.MM_returnValue"/>
</a>
Once again, sorry that I couldn't figure out how to create code blocks.
Clean up your code and define preventExitPop
var preventExitPop = true;
function exitPop() {
if(preventExitPop) {
return "TEXT";
}
}
window.onbeforeunload = exitPop;
changeToFalse() is not a function - change the onclick paramater to preventExitPop = false;

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>

Graceful upgrading of an anchor element

I want to add a JavaScript functionality to an array of thumbnails such that the image would expand upon clicking instead of opening in the current window. I am thinking of having a function within the onclick attribute, but I don't think this work:
<script type='text/javascript'>
function expand(){
this.height = 200;
this.width = 200;
}
</script>
<a href='/image_1.jpg' onclick='expand()'>
<img src='/image_1.jpg'>
</a>
If JavaScript is not enabled, I would like the link to work. Any idea how to go about doing this? Thanks for your time :)
You have to give this as a variable in the function for example ths
<script type='text/javascript'>
function expand(ths){
$(ths).find('img').height('200');
$(ths).find('img').width('200');
return false;
}
</script>
<a href='/image_1.jpg' onclick='expand(this)'>
<img src='/image_1.jpg'>
</a>
And return false says Prusse.
** UPDATED **
If you want to resize image, you must call the image and no link.
Don't use the onclick handler:
Instead:
var elem = document.getElementById("the-id-of-a");
elem.addEventListener('click', function(e) { /* handle event */ e.preventDefault(); return false; });
See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Just make the onclick handler return false. Using inline handlers like in your example:
<a href='/image_1.jpg' onclick='expand(); return false;'>

Categories

Resources