html anchor tag reference - javascript

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);
}

Related

Target _blank not being added to HTML using jQuery

I want to manipulate the DOM using jQuery. In my website, a header is being imported by a widget. I cannot edit this code directly, but a specific anchor in the header should have target _blank. When doing this, nothing happens. I get no error in my console, and nothing changes in the DOM.
I've used this jQuery code:
jQuery(document).ready(function() {
jQuery('#iwgh2-navigation-menu-toggle-animation-wrapper a').attr('target', '_blank');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="iwgh2-navigation-menu-site" style="" href="http://binnenland.vlaanderen.be">Anchor Text</a>
What I have checked:
The code is being executed. When I deliberately write a syntax error, I get an error in my console.
I tried to change the code to use .remove() instead of adding the anchor, but nothing happened as well.
Try using this instead:
jQuery(document).ready(function() {
jQuery('.iwgh2-navigation-menu-site').attr('target', '_blank');
});
I can only assume that the parent element id does not match your selector operator.
The id you use in your JS-code is not present in your HTML.
Add it there and your code will work:
jQuery(document).ready(function() {
jQuery('#iwgh2-navigation-menu-toggle-animation-wrapper a').attr('target', '_blank');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="iwgh2-navigation-menu-toggle-animation-wrapper">
<a class="iwgh2-navigation-menu-site" style="" href="http://binnenland.vlaanderen.be">Anchor Text</a>
</div>
Alternatively you can also just use
jQuery('.iwgh2-navigation-menu-site').attr('target', '_blank');
to add the attribute to every link with the classname.

<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

How should I use an image to trigger Javascript?

To have an image which acts as a javascript trigger there are quite a few options:
(EDIT: using inline css & javascript for simplifying the question)
Image in anchor tag:
<img src="pic.jpg" />
Img tag with properties:
<img style="cursor:pointer" onclick="myFunc();" />
Anchor tag with properties:
Possibly others as well. Is there a (convention|best practice|widely accepted|fail safe) way to go on with this?
I want a small image to act as a button to run certain Javascript or AJAX.
BTW, I've seen this but it's not what I'm looking for, he talks about header elements, not links.
Related: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?
There is no convention on how to use onclick event.
But you should not use inline javascript. As we are in 2012 and a lot of javascript frameworks make your life easier.
Best for you if you move to a javascript library (eg jQuery):
<img src="pic.jpg" id="myPicture" />
<script type="text/javascript">
$(document).ready(function(){
$('#myPicture').on('click', function(){
alert('image clicked');
});
});
</script>
or plain javascript:
<img src="pic.jpg" id="myPicture" />
<script type="text/javascript">
window.onload = function(){
document.getElementById('myPicture').onclick = function(){
alert('image clicked');
};
};
</script>
If I were you I'd stick with your first choice with a few changes
<img src="pic.jpg" border="0" />
Reasons for this are as follows
href="#" still allows clickthrough if your myFunc fails
javascript:void(0) doesn't allow clickthrough
javascript:void(0) is cross-browser
javascript:void(0) still allows basic implied anchor tag behaviour
attribute/properties on the image tag will be recognised by most browsers but some older versions of IE may not like it
if you want to use a background image that's upto you, but it'll mean additional CSS to control height/width
Additionally, if you use jQuery or some other library, then I'd recommend doing it via
$(document).on('ready, function() {
$('#myAnchorId').on('click', myFunc);
});
Instead of doing via HTML props... just in case the user has JavaScript turned off
If you only going to use the image as an trigger, use the second option...
If you're going to use some more for the same thing, you can use an span to...
<span onclick="myFunc();" >
<img src="pic.jpg" style="cursor:pointer" />
if you click the image, or this text, the javascript function will be triggerd....
</span>
Maybe with jQuery ? Your HTML :
<img id="pic" src="pic.jpg" />
With this jQuery :
$('#pic').click(function() {
// Your stuff here
});
And this CSS :
#pic {
cursor: pointer;
}
Inline css and js are never the best way. :)
Use a class to identify your trigger object (be it an anchor or an image) and then perform click handling on that object:
Say the class name is "clickTrigger", then your HTML:
or
<img src="pic.jpg" />
or
<img style="cursor:pointer" class="clickTrigger" />
Then with javascript/jQuery attach to the click event:
Javascript:
var element = this.getElementsByClassName('clickTrigger')[0];
element.onclick = function (event) {
// handler
}
jQuery:
$('.clickTrigger').click(function (event) {
// Handler
});

Is there a best practice for calling JavaScript with parameters from an anchor tag?

I have read the following question
Javascript and Anchor Tags, Best Practice?
And it seems to suggest a solution such as the following
<a id="foo" href="#">Click Me</a>
document.getElementByID("foo").onclick = function() { alert("hi"); }
However suppose that I have a bunch of links all calling the same function with a different parameter. My quick and dirty solution would be to generate something like the following
Click Me 1
Click Me 2
Click Me 3
Is there a way to adapt the listener solution to deal with parameters?
You could use a data attribute along these lines on each element in question:
Click Me 1​
And use the following callback:
document.getElementById("foo").onclick = function() {
alert(this.getAttribute('data-id'));
}​
In fiddle form here.
A better option, though, might be to use jQuery to handle things. Assuming the link format above, that would look like this:
$('#foo').click(function(){
alert($(this).attr('data-id'));
});
You can use delegation.
<div id='links'>
<a href="#" class="link" data-param1='1000' data-param2='something'>click</a>
<a href="#" class="link" data-param1='1001' data-param2='something'>click</a>
<a href="#" class="link" data-param1='1002' data-param2='something'>click</a>
</div>
<script type='text/javascript'>
$links = document.getElementById("links");
$links.onclick=function(e){
element = e.target;
if(element.tagName="a" && element.getAttribute("class")=="link"){
console.log(element.getAttribute("data-param1"))
console.log(element.getAttribute("data-param2"));
}
return false;
}
</script>
Notice that when you have in HTML a code like that:
Click Me 1
It's exactly the same to have in JS:
document.getElementById("foo").onclick = function(event) {
myFunction('1001');
return false;
}
When the parser found an event attribute, it creates an anonymous function in exactly the same way.

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