when i click link to open child window, parent page refresh automatically. how can i stop it?
parent page should not refresh while open child window. how to do this? please help me.
my code is as below given:
<html>
<head>
<title>login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var popup;
function ShowPopup(url) {
if(popup)
{
popup.close();
}
popup = window.open(url, "self", "toolbar=no,scrollbars=yes,location=no,statusbar=no,menubar=no,resizable=0,width=300,height=350,left = 0,top = 0");
popup.focus();
}
</script>
</head>
<body>
Sign In / Register
</body>
</html>
Your page refreshes because not only is your function called, but also the
hyperlink indicated by the a tag is executed. So you have two things happening
at the same time:
the hyperlink itself navigates to whatever is in the href attribute,
even if it is empty. If href is empty it means: reload this page.
the onclick event handler also does something (opening a popup), but it
does currently not cancel the first effect.
In a first reaction one might just remove the offending href
attribute. This solves the problem, but introduces another: you lose all the nice
styling on the displayed hyperlink text (like underline, color, changing cursor, tab order, ...),
which is generally not what you want.
Here are some more convenient solutions:
Let the onclick event handler return false
Returning false will cancel the anchor's default behaviour and the content of the href attribute will be ignored:
onclick="ShowPopup('popup_login.asp'); return false;"
If you care about browsers that have no javascript support (or have it disabled), then put
a meaningful fall-back url in the href attribute, like:
href="javascript_is_required.html"
Use event.preventDefault
This is an alternative to return false. It has the advantage that you can make it
execute as the first instruction, so that if a run-time error occurs in the other code
it will already have done it's job:
onclick="event.preventDefault();ShowPopup('popup_login.asp');"
Note that this event object is defined by all browsers in the context of event attributes,
and is to be distinguished from the window.event object, which is not supported by
all browsers.
Use hash notation in href
Give the anchor a name
and then reference that name in the href attribute. This way
the anchor will navigate itself into view, which
it usually already is when the user clicked it:
name="loginlink" href="#loginlink"
You will often see the shorter variation href="#", but this will scroll the page to the top
when clicked, which might be OK if you know for sure the page is not scrolled down.
Still, the use of "#" has a side-effect: when clicked the url changes and the
previous url is put on the browser's history stack. So if after clicking the link you press the back button,
you stay on the page. This may be undesired.
Use the javascript: protocol to do nothing
href="javascript:"
This will make the hyperlink execute any javascript following the colon, and since there
is none there, nothing will happen. The browser history is not modified. There are variations
to this method, like javascript: return false; or javascript: void(0);
Use the javascript: protocol to handle the click event
With this solution you no longer use the onclick attribute. Instead you move the code
to the href attribute:
href="javascript: ShowPopup('popup_login.asp');"
Separation of lay-out and code
The original code and all the above solutions still have an issue that many developers
do not like: HTML is mixed with javascript code. It is better to separate these two.
This can be done as follows:
<a href="javascript_is_required.html" id="loginLink"
title="Click here to log on"> ... </a>
...
<script>
document.getElementById('mylink').onclick = function(e) {
e = e || event; // cross-browser way to get event object
e.preventDefault(); // cancel the default click behaviour
ShowPopup('popup_login.asp'); // your custom code comes here
return false; // cancel the default click behaviour
};
</script>
A few will say this also
has a down-side: it is harder to identify the code that executes on a click.
The above code will attach the event handler to the click event of the mylink
element. Make sure to have it execute only after the document has loaded.
The event handler cancels the default click
behaviour in two ways. Choose the one you prefer, or both if you want. As it is
cancelled, the navigation to the href attribute value is never executed. The first
line deals with browser specifics as older IE browsers do not pass the event object
as an argument to the event handler, but expose a global event object instead.
If you don't have to support pre-IE9 browsers, you can improve more by using
addEventListener('click', myfunction); instead of onclick = myfunction; in the
above code. This has many advantages: more event handlers can be attached to the same
event, and you can also remove them one by one. jQuery offers good cross browser support
for this with .on().
There are several variations on the above solutions, all with their
benefits and downsides. You could even step away from using an anchor for this purpose
and use another element instead with styling added to it.
Write return false(); after the window.open() JS method.
In case the above snippet is not working, change the default <button> tag to normal <input> tag with type="button". This will solve the problem.
Below is the code snippet:
JavaScript
<script>
function tagedlist() {
window.open("http://w3schools.com","mywindow","menubar=1,resizable=1,width=1000,height=1000");
return false;
}
</script>
Just adding type="button" in <button> tag worked. I know it's redundant but it worked!
From this:
<button id="btnDeleteRequest" class="btn btn-default" accesskey="D" onclick="ExecuteCommand('DeleteRequest',this);">
To this:
<button id="btnDeleteRequest" class="btn btn-default" type="button" accesskey="D" onclick="ExecuteCommand('DeleteRequest',this);">
I had button something like this
html:
<button onclick="captcha()" >Verify Human</button>
js:
function captcha(){
window.open(link,name,"width=800, height=600");
return false;
}
After adding type="button" in html content it worked
<button onclick="captcha()" type="button">Verify Human</button>
I know its redundant but it works ;)
Also thanks to #sojim
Related
The Problem
For site testing, I am attempting to emulate a middle click (or scroll wheel click) on an element like the one below, using JS that is based on some other answers on here.
HTML:
<a
id="example-link" href="https://www.google.com/"
target="_blank"
onclick="window.open('https://www.google.com/', '',
'width=500, height=500, resizable=1, scrollbars=1');
return false;">
<span>Middle Click Me</span>
</a>
JS (looking to change something here):
var middleClick = new MouseEvent( "click", { "button": 1, "which": 2 });
jQuery("#example-link")[0].dispatchEvent( middleClick );
The issue is shown in this jsfiddle.
Note that a regular click should normally dispatch a popup. jsfiddle is catching the popup and opening it in a new tab.
jsFiddle is used instead of a stackoverflow fiddle to avoid confusion, as the stack overflow fiddle doesn't properly handle window.open().
Compare 1) middle-clicking manually to 2) running the code to emulate a click.
The problem is, when I trigger the middle click programmatically, it triggers both the onclick method of opening a new window, as well as opening the link in a new tab (creating both a popup and a tab instead of just a tab). If this link is middle clicked manually, the popup will not trigger.
The Question
Is there a better way of emulating middle clicks (preferably cross-browser compatible)? The way it is written, I can't really get the MouseEvent script to accurately emulate manual middle clicks.
Edit: unfortunately, I can't change the HTML object or modify the DOM for the purpose of testing integrity, so I would prefer that the onclick tag stays on the element.
To the best of my understanding, as long as that inline click handler is there, it will fire on every click event on that element, but here are two workarounds I've come up with.
If you really can't modify the DOM even for an instant, then the first option won't serve. It cheats by changing the DOM and then restoring it, hopefully before anyone notices.
The second option avoids the need to click the link at all by reading its attributes and using them to open a new tab, without firing a new click event. (This relies on the script having a basic understanding of link element's markup. Specifically, the code I've written here simply assumes that the "link" element has a valid url in its href attribute -- but if necessary, you could make other, more complex assumptions, and act conditionally based on the properties that the "link" element turns out to have at runtime.)
Note: A third alternative would be create a custom event that has all the same core behavior as the built-in click event but without actually being a click event, the idea being to fool the onclick handler into sleeping through the event. I'm not sure how much work it would take to do a sufficiently good job of rebuilding this particular wheel. Maybe it wouldn't be too bad?
In this script, the functions that open the new tab are triggered by button clicks, but of course this is just for demo purposes, and you'd presumably trigger them on page load or as callbacks to some other action. And the anchor element in the snippet has been changed slightly, too, for space-saving reasons
.
(Because the direct call to window.open doesn't appear to work properly in the Stack Overflow snippet, I followed your lead and pasted the code into a fiddle so it can be seen running in all its nominal glory.)
const
// Identifies some DOM elements
cheatButton = document.getElementById("cheat-button"),
mimicButton = document.getElementById("mimic-button"),
exampleLink = document.getElementById("example-link"),
// Defines an event to be dispatched programmatically
middleClick = new MouseEvent("click", {button: 1, which: 2});
// Demonstrates calling the functions
cheatButton.addEventListener("click", emulateMiddleClick); // Option 1
mimicButton.addEventListener("click", followLink); // Option 2
// Defines the functions
function emulateMiddleClick(){
const onclickHandler = exampleLink.onclick; // Remembers onclick handler
exampleLink.onclick = ""; // Supresses onclick handler
exampleLink.dispatchEvent(middleClick); // Dispatches middle click
exampleLink.onclick = onclickHandler; // Restores onclick handler
}
function followLink(){
if(!exampleLink.href){ return; } // In case href attribute is not set
const {href, target} = exampleLink; // Gets props by using "destructuring"
// This doesn't seem to work in the Stack Overflow snippet...
window.open(href, (target || "_blank")); // In case target attribute is not set
// ...But we can at least log our intention to open a new tab
console.log(`opening: "${href}" (in "${target}")`);
}
div{ margin: 1em; }
button{ padding: 0.3em; border-radius: 0.5em; }
span{ margin: 1.3em; }
<div>
<button id="cheat-button">Fake Click, and Suppress Handler</button>
</div>
<div>
<button id="mimic-button">Follow Link without Clicking</button>
</div>
<a id="example-link"
href="https://www.google.com/"
target="_blank"
onclick="window.open('https://www.google.com/', '', 'width=50, height=50');">
<span>Middle Click Me</span>
</a>
I am using a OnePage template of bootstrap, I can not click a link, or can not switch a radio button, someone says I am using e.preventDefault()
Open this page http://abi.maxinrui.com/, you will see what I mean when you click "Click me" on that page.
I check the js file, there are lots of e.preventDefault() and I don't know how to modify them.
Is there a way to disable e.preventDefault()?
I want to have some hyperlink to another websites in my OnePage templete, so here is what I am think: I give some particular elements an ID or class, then I write some js, to disable e.perventDefault() only for these elements.
Does anybody know how to do that?
Thanks!
If you're using jQuery to handle your events, then it's possible!
First, a fiddle (shell for full effect): http://fiddle.jshell.net/UN5WE/show/
Here's the actual fiddle to edit: http://jsfiddle.net/UN5WE/
Basically, we're modifying jQuery's Event object, and specifically, the preventDefault method found on the prototype. We maintain a reference to re-enable preventDefault.
EDIT
For your specific use case, here's a way to disable preventDefault (based on a class). Just run this script after jQuery has loaded:
jQuery.Event.prototype.preventDefault = (function(){
var originalFunc = jQuery.Event.prototype.preventDefault;
return function(){
if($(this.target).hasClass('disableDefault')) {return;}
originalFunc.call(this);
}
}())
Prior to calling preventDefault, this will check to see if the target has a disableDefault class. If it does, it returns immediately (allowing the default to happen). To test your page, copy that code into your console and then run: $('h1').addClass('disableDefault').
I don't think is possible, or at least not on an easy way that i can think of, you can unbind the handlers if they were setted using bind, but that will also remove any behavior that they have, but you can use a workaround, add a new event handler for your links, i recommend that you add a special class to external anchors and then get the href attribute from it and open a new tab using window.open like this:
http://jsfiddle.net/yV78E/2/
The html
Hey
The js
// Similar behavior that might be on your site
$('a').click(function(e){
e.preventDefault();
// some code
});
// Use the code below as a workaround
$('.externalLink').click(function(e){
var targetLink = $(this).attr('href');
window.open(targetLink, '_blank');
});
You only need the second part of the script above, since the first one is just to emulate your problem.
I have a standard link setup that fires an event via jquery when clicked
Click Me
All that works great, except that when the pseudo URL is clicked, it appends a hashtag (#) to the url. This hashtag affects how my page reloads if the user decides to refresh the page later on, so i'd like to not have the hashtag appended to the url.
is this possible while still allowing my normal jquery to fire?
Thanks!
You should either return false; from the event handler of A tag
Or, use
Click Me
For those who thinks javascript: void(0) is bad practice
If you use href='#', you must take care of two things
// one
function fn() {
// code
return false;
}
// two
click
And if you forget and just write onclick="fn();" it won't work
Another thing why I used javascript: void(0); is, if the function encounters/throws an error, it wont return false
So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:
Use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
In end of the you click function, use:
return false;
smartass anwser: use a button.
alternative: you must make sure to trigger the preventDefault in youre jQuery event handler
$("dosomthing").click(function(e){
//make magic happen
e.preventDefault()
})
this works on html forms thats submitting and such.
note on the button thing
it is best pratice to only use a tags for link (somthing that changes the url) and buttons for other sorts of interactions.
search bots and other web crawlers expect a tags to link to a other html document (hyperlink) and up to and including html 4. or to a other point in the current document.
Does it need to be an href at all? you could do:
<span class="dosomething">Click me</span>
.
.dosomething{cursor:pointer}
I have an anchor tag in the website as follows:
<a href="http://www.abc.com/..." class="abc-profileinsider-popup">
<img src="..." />
</a>
The problem is that it never redirects the page to href on being clicked.
Whenever I rename the class abc-profileinsider-popup to X-profileinsider-popup where X is any string apart from abc, it works. Can anybody tell the reason behind this behaviour?
You have a javascript function somewhere that is attaching an event to elements with the class: abc-profileinsider-popup.
This function must be returning false meaning the link doesnt process. Try disabling javascript to confirm this, the link should work with Javascript disabled.
Then search for the code and see what its doing :)
I think there's an event handler in your code that prevents the default behaviour, and that it's specifically attached to elements with
abc-profileinsider-popup class.
If that is the case you should find something like:
myAnchor
.addEventListener("click", function (event) {
event.preventDefault();
});
I would search your codebase for occurrences of the string abc-profileinsider-popup.
That's an article I wrote, in case you need more info about W3C event model.
Many times I've seen links like these in HTML pages:
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
What's the effect of the return false in there?
Also, I don't usually see that in buttons.
Is this specified anywhere? In some spec in w3.org?
The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.
I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.
The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.
You can see the difference with the following example:
Google
Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.
WHAT "return false" IS REALLY DOING?
return false is actually doing three very separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jquery-events-stop-misusing-return-false for more information.
For example :
while clicking this link, return false will cancel the default behaviour of the browser.
<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
Here's a more robust routine to cancel default behavior and event bubbling in all browsers:
// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
if (!e)
if (window.event) e = window.event;
else return;
if (e.cancelBubble != null) e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
if (window.event) e.returnValue = false;
if (e.cancel != null) e.cancel = true;
}
An example of how this would be used in an event handler:
// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context)
{
// Find the tabStrip element (we know it's the parent element of this link)
var tabstripElement = this.parentNode;
Tabstrip.showTabByLink(tabstripElement, this);
return eventCancel(evt);
}
Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.
I believe it causes the standard event to not happen.
In your example the browser will not attempt to go to #.
Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.
If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.
using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.
In other words, adding return false stops the href from working. In your example, this is exactly what you want.
In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.
The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.
Browser hack:
http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
Return false will prevent navigation. Otherwise, the location would become the return value of someFunc
The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.
onclick="return false"
I am surprised that no one mentioned onmousedown instead of onclick. The
onclick='return false'
does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but
onmousedown='return false'
does.
In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.
See also event.preventDefault() vs. return false
I have this link on my HTML-page:
<a href = ""
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>
The function setBodyHtml() is defined as:
function setBodyHtml (s)
{ document.body.innerHTML = s;
}
When I click the link the link disappears and the text shown in the browser
changes to "new content".
But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?
It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.
In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.
This example shows why it is sometimes USEFUL to use "return false".
I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".
The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.
When using forms,we can use 'return false' to prevent submitting.
function checkForm() {
// return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
...
</form>
By default, when you click on the button, the form would be sent to server no matter what value you have input.
However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.
So, when the listener received "false", the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.