Firefox link to javascript function opens a new window when not intended - javascript

I have this problem where when I have this html in firefox it opens a new window
<a style="float:right;"
href='javascript:window.location.href="#";'onClick="javascript:addNewRecord();">
New Record</a>
I have tried self.location, window.location, #body, and #h1 as the href.
Originally I had the code as, but in firefox that did not do anything but open a fresh window, and not perform my function. The code works perfect in chrome.
<a style="float:right;" href="javascript:addNewRecord();">New Record</a>

The canonical inline way is
<a style="float:right;" href="#"
onClick="addNewRecord(); return false">New Record</a>
or better:
<a style="float:right;" href="#"
onClick="return addNewRecord()">New Record</a>
where addNewRecord returns false at the end of the function
An even better way is
window.onload=function() {
document.getElementById("addLink").onclick=addNewRecord;
}
function addNewRecord() {
...
return false;
}
plus
<style>
#addLink { float:right }
</style>
and
New Record
Since abusing the HREF on a link going nowhere just to get a pointer is frowned upon, you may consider a <span> with an onclick and a cursor:pointer. It does need more effort to make such an element accessible to for example screen readers.

try :
onClick="addNewRecord();return false"

How your code behaves depends entirely on what the addNewRecord() function does (including what it returns).
Without seeing inside that function it's hard to tell, but I'd say that what is happening is inside there.
Note that what you put in the href="" part probably is not affecting the behaviour you're seeing.

Try this
<a onclick="javascript:addNewRecord();">New Record</a>

Related

How to restrict href link to <oblique> tag

<a href="myList/doctor">
<div>
<span> The important Info
<a data-toggle="modal" data-target="#mapModal">
<a data-toggle="modal" data-target="#mapModal"
id="obliqueIcon"> <oblique
class="iconSize">i</oblique></a>
</a>
</span>
</div>
</a>
document.getElementById("obliqueIcon").onclick = function(e) {
return false; // or use e.stopPropagation() and e.preventDefault()
}
I have the above code.Here the div can be clickable but the 'i' button here should open up a model box (data-target="#mapModal") but it is not since the anchor tag contains the 'href'.
What I am trying to do is let this code should not be changed but when I click on the oblique it should open up a model box but not redirecting to the link.Is there any way to restrict it.Please suggest help.Thanks.
So there are a couple of issues with your HTML: first, there isn't an <oblique> tag (did you mean <i>?), and second, you can't nest an <a> tag within another <a>.
That said, though, the more general form of what you're asking for -- a node within a link tag that will not fire that link if clicked -- is possible; all you need to do is prevent the click event from bubbling up from that node to the anchor tag:
document.getElementById("foo").onclick = function(e) {
// open your modal here
return false; // or use e.stopPropagation() and e.preventDefault()
}
<a href="https://example.com">
This should link to the other page...
<span id="foo">but this should not</span>
</a>
Added to the answer in response to comments below: here's the same code snippet applied to your HTML:
document.getElementById("obliqueIcon").onclick = function(e) {
return false; // or use e.stopPropagation() and e.preventDefault()
}
<a href="myList/doctor">
<div>
<span> The important Info
<a data-toggle="modal" data-target="#mapModal">
<a data-toggle="modal" data-target="#mapModal"
id="obliqueIcon"> <oblique
class="iconSize">i</oblique></a>
</a>
</span>
</div>
</a>
I do not get the error message you're reporting ("Cannot set property 'onclick' of null") but at a guess it may be because you're continuing to use invalid HTML (the nested <a> tags) -- possibly that's making those nodes inaccessible in some browsers? (I'll stress that this is only a guess; I don't have a lot of experience working with invalid HTML other than by fixing it, so I don't have a solid understanding of how all browsers might handle it. I've tested Safari, Chrome and FF, all work correctly even with the invalid HTML, but if you're using a different browser perhaps that's the cause. If you see the error on my second snippet but not on my first snippet, that would confirm the guess. If you see no errors in either snippet, then you have something else going wrong in your code.)

How to pass value of href to javascript and use it in window.location when a hyperlink is clicked?

I have two types of hyperlinks .When the first one is clicked the value of href is passed to function but its value never used in window.location!(Because it opens the link in safari instead of iphone webApp ).When the second hyperlink is called the value of href never get passed to function and again the href value is opened in safari instead of webApp!Could any one help me pass value of href to function and use it in window.location instead of opening it on safari.Thanks in advance.
<li class="x"><a id="1" title="1" href="./test.php?try" onclick="myFunction(location.href=this.href);"> <img id="Button1" src="./1.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">FIRST</div></a></li>
<li class="x"><a id="2" title="2" href="./test.php" onclick="myFunction(location.href=this.href+'?try&appid='+currentID;return false;);"> <img id="Button2" src="./2.png" alt="" width="42" height="42" border="0"><div class="caption" style="color:red">SECOND</div></a></li>
<script>
function myFunction(myLink) {
alert("hello"+myLink);
window.location = myLink;
}
</script>
There are several things at play here. As fiprojects points out, it's best not to do inline JavaScript (some of the reasons are just personal preference). You'll end up repeating yourself and making it hard to maintain your code (among other reasons). Your best bet is to use Event Listeners (w3schools link, not always the best resource, but is sufficient for this example). These are extremely simple if you're using a JavaScript library (jQuery). But being that you requested a JavaScript solution, I'll outline how to do that in my answer.
First, let's format your code to make it easier to read:
<li class="x">
<a id="1" title="1" href="./test.php?try" class="myLink">
<img id="Button1" src="http://placehold.it/360x240">
<div class="caption" style="color:red">FIRST</div>
</a>
</li>
<li class="x">
<a id="2" title="2" href="./test.php" class="myLink">
<img id="Button2" src="http://placehold.it/360x240">
<div class="caption" style="color:red">SECOND</div>
</a>
</li>
I've only made a couple changes here. I removed the JavaScript onclick. I created a placeholder image (just for my own purposes, as I don't have your images, you'll want to put your images back in there). And lastly, I added a class="myLink" to your <a>. This will allow us to reference your links with our event listener a bit more easily.
For the JavaScript
<script>
var linksArray = document.getElementsByClassName("myLink");
var myFunction = function(event) {
event.preventDefault();
var href = this.getAttribute("href");
alert('hello ' + href);
window.location = link;
return false;
};
for (var i = 0; i < linksArray.length; i++) {
linksArray[i].addEventListener('click', myFunction, false);
}
</script>
The first line is creating an array with any elements that have class="myLink". We will loop through this array later, and add the event listener. Before we loop through, we need to create your function.
In order to prevent the default action that occurs when a user clicks the link, we need to stop propagation. So we'll use event.preventDefault() here. I have also added return false; to the function. Both are intended to do the same thing.
Instead of passing a variable, we'll use this to obtain the reference. We'll also use the JavaScript function getAttribute and pass href to it. This will pull the href value for you.
lastly, we are looping through our linksArray. We're adding a click event listener and assigning myFunction as a callback. Now, any time that a user clicks on one of the images, this function will fire off.
And here's a working example on JSFiddle.
You are trying to run before you can walk...
Your javascript needs alot more work. Avoid putting javascript inside html. Thus avoid things like:
onclick="myFunction(location.href=this.href);"
I would use jquery (javascript library) as it would help in the long run as it would lead you to be cross browser compatible.
Your "id" tags should be alphabetic or alphanumeric, not numeric. So id="1" is (I believe) illegal even if it works.
Actually... Sorry.... but the more i think about it, you really need a good book to advance your javascript before attempting what you want to do otherwise you'll fail to understand limitations or risks to some of your work.
Using jquery (which itself is written in javascript) you could change the URL via
$("#link1").click( Change1 );
$("#link2").click( Change2 );
function Change1()
{
$("#link1").href("./test.php?try");
}
function Change1()
{
$("#link2").href("./test.php?try");
}
The above would work if your id tags were renamed from id="1" to id="link1" and id="2" to id="link2"
Sorry I not help more than that...

How to change a word in a h2 when certain page is clicked on

I'm trying to change a certain word in the title of a page dynamically with javascript depending on which link in the nav is clicked on. So for instance, if the "Asia" link is clicked I want the h2 to display: "You are in Asia" or if the "Europe link is clicked I want the h2 to say: "You are in Europe."
The html for the nav bar:
<div id="zone-nav">
<a href="" id="surge-btn"</a>
<a href="" id="latin-btn"</a>
<a href="" id="africa-btn"</a>
<a href="" id="asia-btn"</a>
</div>
The html I have thus far for the title that needs to be changed: `
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>`
I know I need to write a function to determine what link is pressed, but I am a little confused on how to approach this.
if you add some extra markup to your html, you can use a single jQuery event handler:
<div id="zone-nav">
<a class="zone-select" href="" id="surge-btn">Surge?</a>
<a class="zone-select" href="" id="latin-btn">Latin</a>
<a class="zone-select" href="" id="africa-btn">Africa</a>
<a class="zone-select" href="" id="asia-btn">Asia</a>
</div>
now the event handler:
$(document).ready(function() {
$(".zone-select").on("click", function() {
$("#zoneName").html($(this).html());
};
});
Firstly you need to deal with your duplicate id here:
<h2 id="zoneName">You are in<span id="zoneName"></span></h2>
Note we cannot have the same id otherwise we don't know how to get an element by it's id. So remove the uneeded one on the h2:
<h2>You are in <span id="zoneName"></span></h2>
Then add event's to your a tags:
<div id="zone-nav">
<a onclick="update('Surge')" id="surge-btn" >item1</a>
<a onclick="update('Latin')" id="latin-btn" >item2</a>
<a onclick="update('Africa')" id="africa-btn" >item3</a>
<a onclick="update('Asia')" id="asia-btn" >item4</a>
</div>
Note: This can be done purely in JavaScript or be done easily in jQuery. But since you did not mention it I will not be using jQuery. We could iterate through by ClassName and have the links be a class, but that's no more simple then the way above.
For the JavaScript we need to return false to prevent the default behavior of a anchor tag:
function update(text) {
document.getElementById("zoneName").innerHTML = text;
return false;
}
Here is a working Fiddle
Would there be a way to keep the updated text in the even if the page reloads?
Yes there is a way to do this without having to use a server-sided language. What I will do is use HTML 5 web storage, note this will only work for browsers that support HTML 5 (which is all of the modern ones), you can use cookies if you need support for older browsers that work similarly for the following example. In this case I will be using sessionStorage which saves the information even until the browser is closed.
I will emulate a href to the same page for the <a> tags, we need to do this because we need to save out information before we move to a new page. After I save I will call location.reload() that will act as a refresh. Note that you could make this move to an entirely new page as well, just include the script on the new page and use window.location.href = "newPageUrl" ( jsfiddle prevents me from moving to a new page ).
The HTML will be the same but the JavaScript will be updated as followed:
window.onload = function() { // When the page loads
if(sessionStorage.zoneName) { // Check if the session exist
// update the page with the session info
document.getElementById("zoneName").innerHTML = sessionStorage.zoneName;
}
}
function update(text) {
sessionStorage.zoneName = text; // store the text into a session called "zoneName"
location.reload(); // reload the page
return;
}
Here is a working Fiddle
Here's an example of what you could do for the africa-btn (this will require jQuery, I hope that's alright):
$(document).ready(function() {
$("#africa-btn").on("click", function() {
$("#zoneName").html("Africa");
};
// Other buttons here
});
What this is doing is attaching an action to the "click" event of the africa-btn anchor tag. When it's clicked it should update the span's html as described above. You can add further click events in a similar way.
Using $("#africa-btn") to bind the click event is a way to do it specifically for that one button, so you'll have to do it for each id.
This would update the selected zone in the dom
<div id="zone-nav">
<a id="africa-btn" onclick="updateZone('africa'); return false;"> </a>
<a id="asia-btn" onclick="updateZone('asia'); return false;"> </a>
</div>
function updateZone(countryName){
document.getElementById('zoneName').innerText = countryName;
return false;
}
are you looking for something like this :
Simple html and javascript only:
http://jsfiddle.net/q9L37c32/
Asia

How to call JavaScript function instead of href in HTML

I have some mockup in HTML
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
I got the response from server when I sent the request.
With this mockup I got as a response of AJAX request that sends my code to server.
Well, everything is fine but when I click on the link the browser wants to open the function as link; meaning after click I see the address bar as
javascript:ShowOld(2367,146986,2)
means browser thing that's url if I want to do this in firebug that's work. Now I want to do that then when anyone clicks the link then the browser tries to call the function already loaded in the DOM instead of trying to open them in browser.
That syntax should work OK, but you can try this alternative.
<a href="javascript:void(0);" onclick="ShowOld(2367,146986,2);">
or
<a href="javascript:ShowOld(2367, 146986, 2);">
UPDATED ANSWER FOR STRING VALUES
If you are passing strings, use single quotes for your function's parameters
<a href="javascript:ShowOld('foo', 146986, 'bar');">
If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.
E.g.:
<button onclick="ShowOld(2367,146986,2)">
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>
Try to make your javascript unobtrusive :
you should use a real link in href attribute
and add a listener on click event to handle ajax
I use a little CSS on a span to make it look like a link like so:
CSS:
.link {
color:blue;
text-decoration:underline;
cursor:pointer;
}
HTML:
<span class="link" onclick="javascript:showWindow('url');">Click Me</span>
JAVASCRIPT:
function showWindow(url) {
window.open(url, "_blank", "directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}
Your should also separate the javascript from the HTML.
HTML:
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
javascript:
myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);
Just make sure the last line in the ShowOld function is:
return false;
as this will stop the link from opening in the browser.
<a href="#" onclick="javascript:ShowOld(2367,146986,2)">
href is optional for a elements.
It's completely sufficient to use
<a onclick="ShowOld(2367,146986,2)">link text</a>

Help needed in Javascript + Image + HREF

In the above code, I am appending a javascript onclick method to the image tag. When I click the image once and I press back, it should go back to the page it came from. Instead its staying on the same page. Is there any way I can avoid that? (probably set something else instead of href="#"). The reason I set href="#" is to make my cursor turn into hand, other than that it has no use.
This is occuring in Firefox. In IE it works fine.
Please help. Thanks.
The reason I set href="#" is to make
my cursor turn into hand, other than
that it has no use.
You can remove the <a href="#"> and add the cursor: pointer style to the image:
<img src="logo.gif" style="cursor: pointer;" />
... to turn the cursor into a hand.
On the other hand, it is probably better to follow the guidelines for progressive enhancement, as David suggested in another answer.
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi'); return false;"/>
you need add return false; to your onclick events if you don't want to load the link.
<a href="#">
<img src="http://www.google.com/intl/en_ALL/images/logo.gif"
onClick="alert('hi'); return false;"/>
</a>
return false prevents the default action from occurring (in this case navigating to "#"), and then navigating back will return you to the previous page, instead of to the current page without "#".
Follow the pragmatic guidelines for progressive enhancement. In particular: Build on things that work.
Use this instead:
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" onClick="alert('hi')" style="cursor:pointer"/>

Categories

Resources