window.open sends the current window to 0 - javascript

On a page (we'll call it: domain.com/subdirectory/page.html) I have a link like this:
Link
The new window opens perfectly, but the problem is, the pre-existing window gets redirected to {domain.com}/{subdirectory}/0 and I can't figure out why it's adding the 0 to the subdirectory and trying to go there.
I have tried moving the window.open to the onclick and making the href "void(0)" and even changed it to a span with an onclick, but I get the same results no matter which option I try. All I want is for the new window to pop up and for nothing to happen to the page you're already on.
The same thing happens in IE9 and in Chrome.
The reason I am using the window.open and not target="_blank" is because I also want to remove the menu and other stuff from that window to save space.
Answer Discovered
When I summarized the problem, I simplified my code too much as to make it impossible for anyone to answer (not by intention of course). I apologize for this.
Here's the actual window.open command (minus the URL): window.open('[hidden url]'_blank',height='400px',width='450px',location=0,menubar=0,resizable=0,status=0,titlebar=0,toolbar=0);
The problem was the "location=0". When I read a tutorial on window.open, it said to set this to 0 if I didn't want the URL shown. Personally, I didn't care, but I figured, the more real estate for information display the better. As it turns out, "location" is a URL and not a boolean property.
Once I removed the "location=0" it began functioning as expected/desired.
Thank you for trying to help.

Use an onclick and return false from the event handler:
Link
I also recommend separating your Javascript from your HTML. If you just have the one link you could do something like:
<a id="linkid" href="someurl" target="_blank">Link</a>
Then somewhere before your closing </body> tag and after that link tag:
<script>
document.getElementById('linkid').onclick = function(){
window.open('someurl','_blank');
return false;
}
</script>

You need to put it in an onclick event. You need to also add in return false; to stop the browser from following the link.
Link
jsFiddle of it working.
Here's another, slightly cleaner way to do it:
<a id="link" href="#">Link</a>
<script type="text/javascript">
var link = document.getElementById("link");
link.onclick = function() {
window.open('someurl','_blank');
return false;
}
</script>
I don't know your scenario, but this is probably the ideal way to do it:
<a target="_blank" href="someurl">Link</a>
Clean and simple, and it does the exact same thing.

When I summarized the problem, I simplified my code too much as to make it impossible for anyone to answer (not by intention of course). I apologize for this.
Here's the actual window.open command (minus the URL): window.open('[hidden url]'_blank',height='400px',width='450px',location=0,menubar=0,resizable=0,status=0,titlebar=0,toolbar=0);
The problem was the location=0. When I read a tutorial on window.open, it said to set this to 0 if I didn't want the URL shown. Personally, I didn't care, but I figured, the more real estate for information display the better. As it turns out, location is a URL and not a boolean property.
Once I removed the location=0 it began functioning as expected/desired.

You should try to learn JavaScript. Its really powerful and the basic things aren't very hard to learn.
There is an JavaScript object named window with an attribute (variable) called location. That is the URL of your page so, with the window.open(..., location = 0, ...); you were setting the URL of the page you wanted to open as http://the_page_you_are_calling_from_url/0.
So... yes, you were correct that location was the problem.
If you wish, take a look at Mozilla window API

Related

Event.PreventDefault() doesn't always work

I just wanted to make a quick userscript to prevent websites from opening links in new tabs, so I can choose when to do so. Oh boy.
I wanted to use plain javascript; I think it's enough for such an easy task. I was doing all my tests in Quora because that's where I decided I wanted to code that little snippet.
Well, nothing worked. I started simple and went increasing the craziness of my code in light of the failure: the link kept opening no matter how many preventDefault()'s, return false's, prevent[*]Propagation(), eventListeners... Even modifying the dom to strip the a element from its target="_blank".
In the end, I bit my tongue and tried jQuery with this little snippet:
$("a").click(function(event){
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
});
But that didn't do any good either. So I gave up. I then realized that the code seemed to work on other websites. Except on Quora.com. A regular Quora link looks like this:
<a href="http://thewebsite.to/go"
rel="noopener nofollow"
target="_blank"
onclick="return Q.openUrl(this);"
class="external_link"
data-qt-tooltip="thewebsite.to"
data-tooltip="attached">
Link text
</a>
There's plenty of crap there, for sure, but I've been stripping down attributes one by one until the bare bones: and still doesn't work. Best of all is that even though the link opens, event.isDefaultPrevented() returns true!
Why does that happen and how can I fix it?
You are sure that links getting selected?
Maybe this help:
$(document).on('click', 'a', function(e) {
e.preventDefault();
});
The problem is the onclick definition in the a tag. It creates a new on click event listener before your code does anything.
To prevent it you will have to play around with the event order, see this previous question: How to order events bound with jQuery

IE not triggering onclick

For some reason IE won't trigger an onclick event. I have a link in my webpage which should renew a captcha image, but no matter what I try, the onclick event won't trigger. I even tried this to test the onclick event:
<a href="#" id="rc" onclick='alert("test"); return false;'>change image</a>
But nothing happened. I also tried to add the onclick event using js in the window.onload event, same result. All other javascript scripts do work, so js is working. Does anyone has any idea why this doesn't work?
by the way, the event doesn't work in any version of IE, and it does work in any other browser.
Edit: If you want to see the full source, go to: http://www.rosegardenvoorburg.nl/Contact?stackoverflow
The page is in Dutch, but the sourcecode is (of course) HTML, so you must be able to understand that.
edit2: I've found a solution myself, and you're never gonna believe what's wrong:
When I'm logged in to the control panel, a div is added at the top of the page, similar to the one shown in ie7 (which tells you you're browser is too old). However, when I don't add a border to that div, the captcha refresh button doesn't work. This doesn't make any sense at all, but at least I've found a solution...
Try with the below:
<a href="javascript:void(0);" id="rc" onclick='alert("test"); return false;'>change image</a>
Also have a look at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
You are doing it in the wrong order
FIRST add the onload, THEN change the source
var cImg;
function renewCaptcha(){
cImg = new Image();
cImg.onload=function(){document.getElementById("captcha").src = cImg.src;};
cImg.src='/Img/captcha/securimage_show.php?' + Math.random();
}
Few tips to ponder!
check if javascript:alert("test") on your ie address bar pops up the message.
Also check and make sure that javascript option is not turned off.
You may also want to reset your ie settings and see if it work.
Also try to see if same works on your fellow colleague's computer.

Call a lightbox on mouseover?

My doubt is actually pretty simple. I have an image of a V890 server and on mouseover of that image i want to call a lightbox,which shows the specs of that server.
I cant get the code to work. Also never used 'onmouseover' function before so dunno how to write the code.
I have found a useful lightbox called 'lightwondow'.
<strong>Monster Fixed Page</strong> - This page is just plain to big for the browser window unless you maximize a 30 inch monitor.
I need to add a mouseover to this code.
Any help would be appreciated.
Thanks.
Anand.
i think the lightbox is usually load at the onclick event, you have to change that to be able to lauch it onmouseover.
Open the file lightbox.js an change the line:
anchor.onclick = function () {myLightbox.start(this); return false;}
with:
anchor.onmouseover= function () {myLightbox.start(this); return false;}
By the way i think you ahve to add the rel attribute to the anchor:
rel="lightbox"
HTH!

href="javascript:" vs. href="javascript:void(0)"

Our web app is rendered totally on the browser.The server only talks to the browser through JSON messaging.
As a result, we only need a single page for the app and mostly all the <a> tags do not have a real href pointing to other pages.
In my quest of removing unnecessary things I was wondering if I can get rid of the zillions of void(0) we have in our code, as they seem useless:
<a onclick="fn()">Does not appear as a link, because there's no href</a>
fn is called
fn is called too!
Does anybody knows if using href="javascript:" can cause a problem?
It works even on IE7...
Please don't spend your valuable time to tell me inline javascript is bad, as this is generated by a template engine :)
It does not cause problems but it's a trick to do the same as PreventDefault
when you're way down in the page and an anchor as:
click here
you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);
regarding your examples
<a onclick="fn()">Does not appear as a link, because there's no href</a>
just do a {text-decoration:underline;} and you will have "link a-like"
fn is called
fn is called too!
it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.
When using javascript: in navigation the return value of the executed script, if there is one, becomes the content of a new document which is displayed in the browser. The void operator in JavaScript causes the return value of the expression following it to return undefined, which prevents this action from happening. You can try it yourself, copy the following into the address bar and press return:
javascript:"hello"
The result is a new page with only the word "hello". Now change it to:
javascript:void "hello"
...nothing happens.
When you write javascript: on its own there's no script being executed, so the result of that script execution is also undefined, so the browser does nothing. This makes the following more or less equivalent:
javascript:undefined;
javascript:void 0;
javascript:
With the exception that undefined can be overridden by declaring a variable with the same name. Use of void 0 is generally pointless, and it's basically been whittled down from void functionThatReturnsSomething().
As others have mentioned, it's better still to use return false; in the click handler than use the javascript: protocol.
Using 'javascript:void 0' will do cause problem in IE
when you click the link, it will trigger onbeforeunload event of window !
<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
alert( 'oops!' );
};
</script>
</body>
</html>
This method seems ok in all browsers, if you set the onclick with a jQuery event:
Click me!
As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.
you could make them all #'s.
You would then need to add return false; to the end of any function that is called onclick of the anchor to not have the page jump up to the top.
I usually do not use any href and change the aspect with css, making them seems link. Thus you do not have to worry about link effect at all, except for the event handler of your application
a {
text-recoration: underline;
cursor: pointer;
}
javascript:void(0); --> this executes void function and returns undefined. This could have issues with IE.
javascript:; --> this does nothing. safest to create dead links.
'#' --> this means pointing to same DOM, it will reload the page on click.
Why have all the click events as a href links?
If instead you use span tags with :hover CSS and the appropriate onclick events, this will get around the issue completely.

HTML anchor link with no scroll or jump

I have various links which all have unique id's that are "pseudo-anchors." I want them to affect the url hash value and the click magic is all handled by some mootools code. However, when I click on the links they scroll to themselves (or to the top in one case). I don't want to scroll anywhere, but also need my javascript to execute and to have the hash value in the url update.
Simulated sample code:
button 1
button 2
Home
So if you were to click on the "button 1" link, the url could be http://example.com/foo.php#button1
Does anyone have any ideas for this? Simply having some javascript return void kills the scrolling but also kills my javascript (though I could probably work around that with an onclick) but more importantly, prevents the hash value in the url to change.
The whole point of an anchor link is to scroll a page to a particular point. So if you don't want that to happen, you need to attach an onclick handler and return false. Even just adding it as an attribute should work:
button 1
A side of effect of the above is that the URL itself won't change, since returning false will cancel the event. So since you want the URL to actually change, you can set the window.location.hash variable to the value that you want (that is the only property of the URL that you can change without the browser forcing a reload). You can probably attach an event handler and call something like window.location.hash = this.id though I'm not sure how mootools handles events.
(Also you need all of the IDs to be unique)
You can use the code below to avoid scrolling:
linktxt
I'm probably missing something, but why not just give them different IDs?
button 1
button 2
Home
Or whatever convention you'd prefer.
Also, preventDefault
$(your-selector).click(function (event) {
event.preventDefault();
//rest of your code here
}
I found the solution. Here I save an old location from calling href
and restore it after scrolling
<script language="JavaScript" type="text/javascript">
<!--
function keepLocation(oldOffset) {
if (window.pageYOffset!= null){
st=oldOffset;
}
if (document.body.scrollWidth!= null){
st=oldOffset;
}
setTimeout('window.scrollTo(0,st)',10);
}
//-->
</script>
and in body of page
<a href="#tab1" onclick="keepLocation(window.pageYOffset);" >Item</a>
Thanks to sitepoint
An easier way would probably be to add it as a GET. That is, http://example.com/foo.php?q=#button1 instead of http://example.com/foo.php#button1
This won't have any effect on how the page is displayed (unless you want it to), and most scripting languages already have tools in place to easily (and safely) read the data.
Well here we are 7 years after this answer was published and I found a different way to make it work: just point the window.location.hash to a non-existent anchor! It doesn't work for <a>s but works perfectly in <div>s.
<div onclick="window.location.hash = '#NonExistentAnchor';">button 1</div>
Worked fine in Chrome 56, Firefox 52 and Edge (IE?) 38. Another good point is that this doesn't produce any console errors or warnings.
Hope it helps somebody besides me.
There is a solution without any JavaScript at all:
I will not jump to the top
Use
button 1
where
function setHash(hash) {
event.preventDefault();
history.pushState(null, null, "#"+hash);
}
event.preventDefault() stops browser from what it normally would do on clicking, and history.pushState adds to the sessions history stack.
For further discussion, see here and here

Categories

Resources