<a> onclick function not working - javascript

My function is not fired when the tag is clicked. Here is my code:
HTML:
<div data-role="footer">
<div data-role="tabstrip" id="tabs">
Home
Settings
<a onclick="signOff()" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
</div>
</div>
JavaScript:
function signOff() {
console.log("something");
VCare.VCareWebService.signOff({cache:false,
callback:function(xml) { // invoke the service
// use jQuery to extract information we are interested in
console.log(xml);
}
});
}

You can't have both an onClick function and valid href attribute in <a>.
Change your anchor element to:
<a onclick="signOff()" href="javascript:void(0)" data-icon="settings" id="contacts">Log Out</a>
You can redirect the page using javascript if you want to.

Another way is to make sure that your onclick returns a false to stop the default event from running.
<a onclick="signOff(); return false" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
Or..
<a onclick="return signOff();" href="views/home.html" data-icon="settings" id="contacts">Log Out</a>
function signOff() {
console.log("something");
VCare.VCareWebService.signOff({cache:false,
callback:function(xml) { // invoke the service
// use jQuery to extract information we are interested in
console.log(xml);
}
});
return false;
}

you need to change your A tag to
<a href="javascript:signOff();
window.location = "views/home.html" data-icon="settings" id="contacts">Log Out</a>

I would recommend not using the onclick method. Not only does it apparently conflict with the default href operation, but it can also cause some minor visual issues where clicking in the margins of the element, etc., can call the function without highlighting the text the way you would expect in a normal link.
Instead, use:
Log Out
Then just change the page address programatically in the signOff function, using this.document.location.href = location or similar
EDIT: it's looking like window.location works better. +1 for Omar, looks like he has the same answer

Related

How to make both href and jquery click event work

I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>
I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.
You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();
Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle

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

html anchor tag reference

i have an anchor tag as below.
<a style="border:0px" href='javascript:deleteAttachment(this);' />
Inside the deleteAttachment, how can i get the anchor tag. Sending this to the method, sends the window element to the method.
function deleteAttachment(ancElement){
//Jquery operation on acnElement
}
Please helop me out.
I would recommend a slightly different approach, since what you're trying to do is a bit old.
assuming you already loaded jQuery, here we go:
<a id="myFirstLink" href="someHref" />
<a class="otherLinks" href="secondHref" />
<a class="otherLinks" href="thirdHref" />
<script>
$(function() {
$('#myFirstLink, .otherLinks').click( function(event) {
// stops the browser from following the link like it would normally would
event.preventDefault();
// do something with your href value for example
alert( $(this).attr('href') );
});
});
</script>
So basically what you can do is this: simply generate all your anchors like you would normally would and apply the same class name to each of them - in my example the class would be "otherLinks".
After that, all your links will be handled by that anonymous function.
Use the onclick handler:
<a onclick="deleteAttachment(this)">
or, the cleanest and most accepted method nowadays, have just the raw link in the HTML:
<a id="deleteAttachment">
and add the click event programmatically, in a separate script block, on DOM load:
document.getElementByID("deleteAttachment").onclick =
function() { ... you can use "this" here .... }
you must set its ID attribute
<a id="myAnchor" style="border:0px;" href="javascript:deleteAttachment('myAnchor');"/>
then use jquery to find it
function deleteAttachment(ID)
{
var MyAnchor = $('#'+ID);
}

inline javascript in href

How can you do something like this:
<a href="some javascript statement that isn't a function call;" >myLink</a>
And have the js in the href execute when the link is clicked.
Just put the JS code directly in there:
fsljk
Though, you should not be doing inline scripting. You should unobtrusively attach event handlers.
<a id="lol" href="/blah">fdsj</a>
<script>
document.getElementById('lol').onclick=function() {
/* code */
};
</script>
<a href="javascript:var hi = 3;" >myLink</a>
Now you can use hi anywhere to get 3.
You can write inline-code in the same way as
<a href="javascript:[code]">
This method is also available in other tags.
addition
if you want to Execution when something tag clicking, you can fix with onClick attribute
<a onClick="function()">
I know this question is old but I had a similar challenge dynamically modifying the href attribute that sends an email when the anchor tag is clicked.
The solution I came up with is this:
$('#mailLink,#loginMailLink,#sbMailLink').click(function () {
this.setAttribute('href', "mailto:" + sessionStorage.administrator_mail_address + "?subject=CACS GNS Portal - Comments or Request For Access&body=Hi");
});
<a id="loginMailLink" href= "#" style="color:blue">CACS GNS Site Admin.</a>
I hope that helps.

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>

Categories

Resources