function createListItem(text1) {
var link = document.createElement("a");
var text = text1;
link.setAttribute("name", text);
link.setAttribute("href", "javascript:updateLevel1(text)");
//link.setAttribute("onclick", "updateLevel1()");
var list_item = document.createElement("li");
var list_text = document.createTextNode(text);
list_item.appendChild(list_text);
link.appendChild(list_item);
return link;
}
function updateLevel1(text) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", text);
link.setAttribute("href", "javascript:updateLevel1(text)");
link.appendChild(document.createTextNode(text));
document.getElementById("navigation_frame1").appendChild(link);
}
Here i want to pass the object text to the function updateLevel1 when i dynamically created an HTML link but unfortunately above code is not working. The function updateLevel1 is not able to figure out the object text. Am i doing something wrong?
Yes, you're doing something incorrectly. First, instead of setting the "href" attribute, you can add a "click" handler to the element:
var link = document.createElement('a');
link.onclick = function() { updateLevel1(text); };
There's really no reason to use "javascript:" URLs in a case like this.
Now, another problem you've got is that you create that <a> element but you don't append it to the document (in the code you posted). I suppose that somewhere, you use the return value from the "createListItem()" function and append it then. If not, well, nothing will really happen.
The reason that your "javascript:" value for "href" doesn't work is that you're setting up a situation wherein the browser will create a function from that string when the <a> is clicked. At that point, the local variable "text" from that function is long gone. When you use an actual function reference bound to the "onclick" property of the <a>, however, your function will retain access to that variable in its closure.
Just use an event handler:
function createListItem(text1) {
var link = document.createElement("a");
var text = text1;
link.setAttribute("name", text);
link.setAttribute("href", "#");
link.onclick = function(){
updateLevel1( text );
return false;
};
var list_item = document.createElement("li");
var list_text = document.createTextNode(text);
list_item.appendChild(list_text);
link.appendChild(list_item);
return link;
}
function updateLevel1(text) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", text);
link.onclick = function(){
updateLevel1( text );
return false;
};
link.setAttribute("href", "#" );
link.appendChild(document.createTextNode(text));
document.getElementById("navigation_frame1").appendChild(link);
}
You'll need to break your string and insert the value text has literally.
link.setAttribute("href", "javascript:updateLevel1('" + text + "')");
Just be careful - you may need to clean text if it contains any single quotes.
If this is a possibility you'll want to run something like text = text.replace("'", "\\'");
Try link.setAttribute("href", "javascript:updateLevel1(this);
Then you read it inside your function by its reference. eg:
function updateLevel1(elm) {
clearNavFrame2();
var link = document.createElement("a");
link.setAttribute("name", elm.name);
...
}
Related
I am trying to dynamically add an anchor element through Javascript. The problem I have is the onclick event is not firing. I believe the problem is how I am generating the HTML. I am creating an array and then push my HTML code to the array. After I have created my output I am joining the array and then adding it to the div tag I have.
var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
//do something specific with rowItem variable
alert(rowItem);
}
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
<div id="mainViewer"></div>
When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.
Any ideas?
I will have multiple anchor links and I don't want to hardcode the function name. I want the onclick event to fire whatever function the itemLink Object has set.
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.
So, what is the solution? to push a DOM element instead of string, something like this:
//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}
var itemLink = {
LinkName: "Edit User",
LinkListClass: "",
LinkListRole: "",
LinkFunction: function() {
//do something specific with rowItem variable
alert(rowItem);
}
};
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)
<div id="mainViewer"></div>
Thanks to #David Thomas for his comment :)
I have made a Javascript link maker...
document.write('http://imgur.com'.link('http://www.imgur.com'));
How I can make this open the link target in a new window, like target="blank"?
Here's a new "link builder" to override the built in link function, and its usage:
function mylink(url) {
return "" + this + ""
}
String.prototype.link = mylink
document.write('http://imgur.com'.link('http://www.imgur.com'));
You can use a function to add a link to a container. E.g.:
<div id="container"></div>
And the Javascript is:
addLink('value', 'http://jsfiddle.net');
function addLink(text, url){
var mydiv = document.getElementById("container");
var a = document.createElement('a');
a.setAttribute('href',url);
a.setAttribute('target','_blank');
a.innerHTML = text;
mydiv.appendChild(a);
}
This is a working JSFiddle JSFiddle
Might be a very simple javascript injection question, but say I have an image html tag:
<img src="rainbow.gif">
I wanted to perform a javascript, such that when clicked on the image, it doesn't go to the myfile.htm. In other words, I wanted to strip the a href which surrounds the img. How can I do this in javascript? Say that I have the following to reference the image tag:
document.elementFromPoint(%f, %f)
f can be replaced by any double/float value
If you have a reference to the img element, then its parent (parentNode) will be the link (in the structure you've given). Three options:
Remove the link entirely
Disable the link
Change the link's href
1. Remove the link entirely
You can remove the link entirely by doing this:
var link = img.parentNode,
linkParent = link.parentNode;
linkParent.insertBefore(img, link);
linkParent.removeChild(link);
That uses parentNode to find the parent and grandparent, insertBefore to move the image, and removeChild to remove the link. Note that this assumes the image is the only thing in the link.
2. Disable the link
If you want to keep the link but render it useless, you can do this:
var link = img.parentNode;
if (link.addEventListener) {
link.addEventListener("click", function(event) {
event.preventDefault();
}, false);
}
else if (link.attachEvent) {
link.attachEvent("onclick", function() {
return false;
});
}
else {
link.onclick = function() {
return false;
}
}
3. Change the href of the link:
This is trivial, just set the href property of the link element (which you can get because it's the parent node of the image) to whatever you want:
img.parentNode.href = /* ...something else */;
For instance:
img.parentNode.href = "http://stackoverflow.com";
...would change the link to point to Stack Overflow.
Live example
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
<a id="anchorWithImage" href="myfile.htm"><img src="rainbow.gif"></a>
Why not grab the anchor, then set its href to nothing:
var a = document.getElementById("anchorWithImage");
a.href = "javascript:void(0)";
Or grab it and set its click event to cancel the default action, which is to browse to the location of its href property
a.onclick = function(e) {
e.preventDefault();
}
Or do you want to grab all anchors that have an image as their child element, and strip out their href?
jQuery would make this easy, if that's an option for you
$("a").filter(function() {
return $(this).children("a").length === 1;
}).attr("href", "javascript:void(0)");
or
$("a").filter(function() {
return $(this).children("a").length === 1;
}).click(function() { return false; }); //returning false from jQuery handlers
//prevents the default action
EDIT
If you were to have a reference to the image, and wanted to set its parent's anchor's href, you'd grab it with the parentNode property:
var img = document.getElementById("imgId");
var a = img.parentNode;
a.href = "javascript:void(0)";
With jQuery you could use something similar to this
$("a").has("img").click(function(e).preventDefaults();});
Basically all this line does is identifies all tags within the document containing an tag disables standard event process
From your comment on another answer, it sounds like you actually want to change/eliminate the target of links at a specific position in the page. You could do something like this:
var el = document.elementFromPoint(10, 10);
while(el) {
if(el.nodeName.toLowerCase() == 'a')
el.href = 'javascript:';
el = el.parentElement;
}
This would loop up from the selected element, identify if the element is an anchor, and set the href to something that does nothing.
you can change the href of a tag on window load itself, so you need not worry when it is clicked.
window.onload = fundtion(){
var imgs = document.getElementsByTagName('img');
for(var i=0;i<imgs.length;i++){
var parentElem = imgs[i].parentNode;
if(parentElem.tagName === 'A')
parentElem.setAttribute("href", "javascript:void(0)");
}
};
I have a list of href / text that I need to make anchors for and then display those anchors. Everything is fine until I actually click any of the anchors. They each only open a tab for the last href. I.e. if the href of the last element in the list is href_n, then every anchor links to href_n, even if the 'href' attribute is different.
//Current basic setup:
loop through list:
anchor = doc.create('a')
divElem = doc.create('div')
anchor.setAttribute('class', 'foo')
anchor.setAttribute('href', 'bar')
anchor.innerHTML = 'mytext'
anchor.addEventListener('click', function() {chrome.tabs.create({url: 'myurl'})});
divElem.appendChild(anchor)
container.appendChild(anchor)
Previously I tried using .onClick, but I kept having a problem with the event listener trying to just attach to the url. I am very amenable to a cleaner solution though that involves something simpler than an eventlistener.
Thanks much.
You mostly just need to change your click handler to not use variables that are not still valid. Here's sample code:
var urlList = [
"aaaa",
"bbbb",
];
var textList = [
"text1",
"text2"
];
function createAnchors(urls, text, container) {
for (var i = 0; i < urls.length; i++) {
var a = document.createElement("a");
var div = document.createElement("div");
a.href = urls[i];
a.innerHTML = text[i];
a.className = "foo";
a.addEventListener("click", function() {
chrome.tabs.create({url: this.href});
return(false);
});
div.appendChild(a);
container.appendChild(div);
}
}
The issue is that any variables in your event listener function are not evaluated until the click. So, in this case, you can avoid using them by just getting the url directly from the clicked link.
I hope you also realize that older versions of IE don't support addEventListener. This mozilla page shows you how you can handle that in the Internet Explorer section.
You need to create a closure:
var urls = [];
for(var i=0;i<urls.length;i++){
anchor.addEventListener('click',
(function(url) {
return function() {
chrome.tabs.create({url: url})
}
})(urls[i])
);
}
I have a string for a title and a string for a link. I'm not sure how to put the two together to create a link on a page using JavaScript. Any help is appreciated.
The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs. I would like to link the titles to the URL to make the page useful.
I am using jQuery but am completely new to it and wasn't aware it could help in this situation.
<html>
<head></head>
<body>
<script>
var a = document.createElement('a');
var linkText = document.createTextNode("my title text");
a.appendChild(linkText);
a.title = "my title text";
a.href = "http://example.com";
document.body.appendChild(a);
</script>
</body>
</html>
With JavaScript
var a = document.createElement('a');
a.setAttribute('href',desiredLink);
a.innerHTML = desiredText;
// apend the anchor to the body
// of course you can append it almost to any other dom element
document.getElementsByTagName('body')[0].appendChild(a);
document.getElementsByTagName('body')[0].innerHTML += ''+desiredText+'';
or, as suggested by #travis :
document.getElementsByTagName('body')[0].innerHTML += desiredText.link(desiredLink);
<script type="text/javascript">
//note that this case can be used only inside the "body" element
document.write(''+desiredText+'');
</script>
With JQuery
$(''+desiredText+'').appendTo($('body'));
$('body').append($(''+desiredText+''));
var a = $('<a />');
a.attr('href',desiredLink);
a.text(desiredText);
$('body').append(a);
In all the above examples you can append the anchor to any element, not just to the 'body', and desiredLink is a variable that holds the address that your anchor element points to, and desiredText is a variable that holds the text that will be displayed in the anchor element.
Create links using JavaScript:
<script language="javascript">
<!--
document.write("<a href=\"www.example.com\">");
document.write("Your Title");
document.write("</a>");
//-->
</script>
OR
<script type="text/javascript">
document.write('Your Title'.link('http://www.example.com'));
</script>
OR
<script type="text/javascript">
newlink = document.createElement('a');
newlink.innerHTML = 'Google';
newlink.setAttribute('title', 'Google');
newlink.setAttribute('href', 'http://google.com');
document.body.appendChild(newlink);
</script>
There are a couple of ways:
If you want to use raw Javascript (without a helper like JQuery), then you could do something like:
var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";
// and append it to where you'd like it to go:
document.body.appendChild(element);
The other method is to write the link directly into the document:
document.write("<a href='" + link + "'>" + text + "</a>");
<script>
_$ = document.querySelector .bind(document) ;
var AppendLinkHere = _$("body") // <- put in here some CSS selector that'll be more to your needs
var a = document.createElement( 'a' )
a.text = "Download example"
a.href = "//bit\.do/DeezerDL"
AppendLinkHere.appendChild( a )
// a.title = 'Well well ...
a.setAttribute( 'title',
'Well well that\'s a link'
);
</script>
The 'Anchor Object' has its own*(inherited)* properties for setting the link, its text. So just use them. .setAttribute is more general but you normally don't need it. a.title ="Blah" will do the same and is more clear!
Well a situation that'll demand .setAttribute is this: var myAttrib = "title"; a.setAttribute( myAttrib , "Blah")
Leave the protocol open.
Instead of http://example.com/path consider to just use //example.com/path.
Check if example.com can be accessed by http: as well as https: but 95 % of sites will work on both.
OffTopic: That's not really relevant about creating links in JS
but maybe good to know:
Well sometimes like in the chromes dev-console you can use $("body") instead of document.querySelector("body") A _$ = document.querySelectorwill 'honor' your efforts with an Illegal invocation error the first time you use it. That's because the assignment just 'grabs' .querySelector (a ref to the class method). With .bind(... you'll also involve the context (here it's document) and you get an object method that'll work as you might expect it.
Dynamically create a hyperlink with raw JavaScript:
var anchorElem = document.createElement('a');
anchorElem.setAttribute("href", yourLink);
anchorElem.innerHTML = yourLinkText;
document.body.appendChild(anchorElem); // append your new link to the body
A dirty but quick way to create elements:
const linkHTML = `<a
class="my-link"
style="position: absolute; right: 0"
href="https://old.reddit.com"
title="Go to old reddit"
>
Old Reddit
</a>`;
// create element
const linkEl = strToElement(linkHTML);
// add element to document.body
document.body.appendChild(linkEl);
// utility function that converts a string to HTML element
function strToElement(s) {
let e = document.createElement('div');
const r = document.createRange();
r.selectNodeContents(e);
const f = r.createContextualFragment(s);
e.appendChild(f);
e = e.firstElementChild;
return e;
}
You paste this inside :
Click here