Javascript: open new page in same window - javascript

Is there an easy way to modify this code so that the target URL opens in the SAME window?
click here``

<script type="text/javascript">
window.open ('YourNewPage.htm','_self',false)
</script>
see reference:
http://www.w3schools.com/jsref/met_win_open.asp

The second parameter of window.open() is a string representing the name of the target window.
Set it to: "_self".
click here
Sidenote:
The following question gives an overview of an arguably better way to bind event handlers to HTML links.
What's the best way to replace links with js functions?

Go;

try this it worked for me in ie 7 and ie 8
$(this).click(function (j) {
var href = ($(this).attr('href'));
window.location = href;
return true;

Here's what worked for me:
<button name="redirect" onClick="redirect()">button name</button>
<script type="text/javascript">
function redirect(){
var url = "http://www.google.com";
window.open(url, '_top');
}
</script>

I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)
$(function() {
$('a[href$="url="]') // all links whose href ends in "url="
.each(function(i, el) {
this.href += escape(document.location.href);
})
;
});
and write your HTML like this:
...
the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.
All this said, it looks like you're using PHP... why not add it in server-side?

So by adding the URL at the the end of the href, Each link will open in the same window? You could also probably use _BLANK within the HTML to do the same thing.

try
<a href="#"
onclick="location='http://example.com/submit.php?url='+escape(location)"
>click here</a>

Related

window.location problem

I am facing on strange problem in ie6.
When i am using window.location to redirect page through javascript it works fine in all browser except ie6.
It works in ie 6 if i place just like below:
demo
but its not working for below code.
<a href="javascript:void(0);" onclick="javascript:redirect();>demo</a>
function redirect()
{
window.location('http://www.demo.com');"
}
can you please figure out that whats problem here.
Thanks.
Avinash
The javascript: protocol is only used if you have Javascript code in an URL. If you put it in an event handler it becomes a label instead.
The location member is not a function, it's an object. Set the href property to change the location.
You have an extra quotation mark after the code line in the function, which is probably causing a syntax error.
<a href="javascript:void(0);" onclick="redirect();>demo</a>
<script type="text/javascript">
function redirect() {
window.location.href = 'http://www.demo.com';
}
</script>
How about doing this:
<a href="#" onclick="redirect(); return false;">
demo
</a>
If you want the page to redirect to demo.html when the user clicks a link, dare I suggest you use the universal, crossbrowser demo?
Try:
window.location.href = 'http://www.demo.com';
in the function.
Try:
window.event.returnValue = false;
document.location.href='http://www.demo.com';

Executing JavaScript when a link is clicked

Which is preferable, assuming we don't care about people who don't have JavaScript enabled?
Or
Is there any difference?
Or there any other ways I'm missing besides attaching an event to the anchor element with a JavaScript library?
The nice thing about onclick is you can have the link gracefully handle browsers with javascript disabled.
For example, the photo link below will work whether or not javascript is enabled in the browser:
foobar
it's better to use the onclick because that's the way the things should be.
The javascript: was somekind of hackish way to simulate the onclick.
Also I advice you to do some non intrusive Javascript as much as possible, it make the code more easy to read and more maintainable!
href="#" has a number of bad side effects such as showing # in the browser footer as the destination URL, and if the user has javascript disabled it will add a # at the end of their URL when they click the link.
The best method IMHO is to attach the handler to the link in your code, and not in the HTML.
var e = document.getElementById("#myLink");
e.onclick = executeSomething;
This is essentially the pattern you'd want to follow:
Write your HTML markup
Attach event handlers from JavaScript
This is one way:
<a id="link1" href="#">Something</a>
<script type="text/javascript">
// get a reference to the A element
var link1 = document.getElementById("link1");
// attach event
link1.onclick = function(e) { return myHandler(e); };
// your handler
function myHandler(e) {
// do whatever
// prevent execution of the a href
return false;
}
</script>
Others have mentioned jQuery, which is much more robust and cross-browser compatible.
Best practice would be to completely separate your javascript from your mark up. Here's an example using jQuery.
<script type="text/javascript">
$(function() {
$('a#someLink').click( function() {
doSomething();
return false;
});
});
</script>
...
some text
Yes I would agree to use onclick and leave the href completely out of the anchor tag... Don't know which you prefer to do but I like to keep the 'return false' statement inside by function as well.
The main difference is that:
The browser assume by default the href attribute is a string (target url)
The browser knows that in a onclick attribute this is some javascript
That's why some guys specify to the browser "hey, interpret javascript when you read the href attribute for this hyperlink" by doing ...
To answer the question, that's the difference!
OTOH what's the best practice when using javascript events is another story, but most of the points have been made by others here!
Thanks

JavaScript: changing the value of onclick with or without jQuery

I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps

Adding an anchor to generated URLs

I have tried finding a simialr example and using that to answer my problem, but I can't seem to get it to work, so apologies if this sounds similar to other problems.
Basically, I am using Terminal Four's Site Manager CMS system to build my websites. This tool allows you to generate navigation elements to use through out your site.
I need to add a custom bit of JS to append to these links an anchor.
The links generated are similar to this:
<ul id="tab-menu">
<li>test link, can i rewrite and add an anchor!!!</li>
</ul>
I can edit the css properties of the link, but I can't figure out how to add an anchor.
The JQuery I am using is as follows:
<script type="text/javascript" src="http://jquery.com/src/jquery-latest.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// everything goes here
$("#tab-menu").children("li").each(function() {
$(this).children("a").css({color:"red"});
});
});
</script>
Thanks in advance for any help.
Paddy
sort of duplicate of this:
How to change the href for a hyperlink using jQuery
just copy the old href and add anchor to it and paste that back
var link = $(this).children("a").attr("href");
$(this).children("a").attr("href", link+ "your own stuff");
A nice jQuery-based method is to use the .get(index) method to access the raw DOM element within your each() function. This then gives you access to the JavaScript link object, which has a property called 'hash' that represents the anchor part of a url. So amending your code slightly:
<script type="text/javascript">
$(document).ready(function(){
// everything goes here
$("#tab-menu").children("li").children("a").each(function() {
$(this).css({color:"red"}).get(0).hash = "boom";
});
});
Would change all the links in "#tab_menu li" to red, and attach "#boom" to the end.
Hope this helps!
I can now target the html by using the following:
$(this).children("a").html("it works");
I assumed that:
$(this).children("a").href("something");
would edit the href but I am wrong.
Paddy
I am not sure for the answer, I dint try
$("#tab-menu").children("li").children("a").each(function() {
// $(this).css({color:"red"}).get(0).hash = "boom";
var temp_url = $(this).href +'#an_anchor';//or var temp_url = $(this).attr('href');
$(this).attr('href', temp_url);
});

How to navigate href in anchor tag via JavaScript

Is there an easy way to have JavaScript mimic a User clicking an anchor tag on a page? That means the Referrer Url needs to be set. Just setting the document.location.href doesn't set the Referrer Url.
<script>
$(document).ready(function () {
$("a").click();
});
</script>
Go here
This doesn't work because there isn't a Click() event setup for the link.
You could do:
window.location = $("a").attr("href");
If you want to keep the referrer, you could do this:
var href = $('a').attr('href');
$('<form>').attr({action: href, method: 'GET'}).appendTo($('body')).submit();
It is hackish, but works in all browsers.
document.location.href = "#wanted_Location";
Maybe something like this is what you're looking for?
$(document).ready(function () {
$("a").each(function(){
if($(this).click()){
document.location.href = $(this).attr("href");
}
});
});
There is a simpler way to achieve it,
HTML
Bootstrap is life
JavaScript
// Simulating click after 3 seconds
setTimeout(function(){
document.getElementById('fooLinkID').click();
}, 3 * 1000);
Using plain javascript to simulate a click.
You can check working example here on jsFiddle.
Okay, referer doesn't get set using document.location (as per my other answer), might work with window.navigate(url)? If that doesn't work the following might, though it's quite - ehrm - ugly:
$(function() {
$("a").each(function(){
if($(this).click()){
$('<form method="get" action="' + $(this).attr("href") + '"></form>').appendTo("body").submit();
return false;
}
});
});

Categories

Resources