javascript getting the html element that fired the onclick function - javascript

I have the following html code:
<a class="button-dashboard-save" href="#" onclick="return interface.saveChanges();">Save</a>
inside the interface.saveChanges() i want to get the element object that fired that function, I mean the whole a element.
Regards,

If I have understood correctly, you want to reference the anchor element <a> inside interface.saveChanges. In this case you can directly pass the this keyword to the function. The code should look like:
<a class="button-dashboard-save" href="#"
onclick="return interface.saveChanges(this);">Save</a>

Use this inside the inline onclick. It will pass the current clicked element in your case.
<a class="button-dashboard-save" href="#" onclick="return interface.saveChanges(this);">Save</a>

Define a event handler function ( using jquery for simplicity ):
$(".button-dashboard-save").click ( function ( eve ) {
return interface.saveChanges ( eve.target );
});
This provides interface.saveChanges with the triggering element as a parameter.
Your html slightly simplifies:
<a class="button-dashboard-save" href="#">Save</a>

Related

make href call a method in reactjs

I would like to make the href attribute of my anchor tag to call a method instead of going to some url. I know that in plain js I can do this:
..href={"javascript: foo(value)">
So I've done the same in my jsx file:
<a href={javascript: ()=>foo(value)}>Click Here!</a>
but it doesn't work.
How it can be done?
use reacts onClick
You can use onClick on an element in react.
like this
<a onClick={()=>foo(value)}>Click Here!</a>
That being said, if the purpose of your a tag is not to go to a link then your html is incorrect and you should think about using a button tag instead
in React use onClick to do the job
<a onClick={() => doSomething("Hello") }>Click Me</a>

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...

<a> onclick function not working

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

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.

Categories

Resources