Javascript link making target blank? - javascript

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

Related

How to create element in background script?

I'm doing this in background script:
var link = document.createElement('div');
Then link is null. I guess it's because extensions background page have no DOM, or am i have no access to it?
Anyway i'm need this to make copy to clipboard. Here part where i'm try to use it:
function selectionOnClick(info, tab) {
var link = document.createElement('div');
var range = document.createRange();
link.innerHTML = ShortURL(info.selectionText);
range.selectNode(link);
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
if (!successful) {
alert("Your browser doesn't support copy to clipboard.");
}
} catch(err) {
alert("Your browser doesn't support copy to clipboard.");
}
window.getSelection().removeAllRanges();
link.parentNode.removeChild(link);
}
chrome.contextMenus.create({'title': 'Short selected', 'contexts':['selection'], 'onclick':selectionOnClick});
You have created the node but have not append it to anything. Append it to body:
document.getElementsByTagName('body').appendChild(link);
just make the "link" variable global then initialize it inside the function..
var link = null;
function selectionOnClick(info, tab) {
link = document.createElement('div');
.
.
.

Getting HTML value from Tinymce

Is there a way to get HTML contents from TinyMCE editor using jQuery so I can copy this over to another div?
I tried several methods like val() on content but it doesn't seem to be working...
if you are initilizing with jquery adaptor
$(selector).tinyMCE().getContent();
Using jQuery:
<textarea id="content" name="content">
$('#content').html()
Using TinyMce API:
$('#content').tinymce().activeEditor.getContent() // overall html
$('#content').tinymce().activeEditor.getContent({format : 'text'}) // overall text
$('#content').tinymce().selection.getContent() // selected html
$('#content').tinymce().selection.getContent({format : 'text'})) // selected text
if you are using tinymce, i would use it's internal methods to get the content you need. when i need to get content within the active editor, i do this:
var rawString = tinyMCE.activeEditor.getContent();
i invoke that method within an event handler function.
here is the documentation:
tinymce api
use TinyMCE's API to get it:
alert(tinyMCE.activeEditor.getContent());
Use text(); instead of val();.
I was trying charlietfl method: $(selector).tinyMCE().getContent();
There was an error:
[$(selector).tinyMCE().getContent();][1]
This way with activeEditor worked for me:
activeEditor
tinymce.activeEditor.getContent()
Source
Here is my code:
$(document).ready(function() {
$(document).on("click", ".btnClassClose", function () {
var tinyMCEcontent = tinymce.activeEditor.getContent();
var getAttrIDArray = [];
$("#" + getelementId).html("");
$("#" + getelementId).html(tinyMCEcontent);
$("#" + getelementId).append(buttonEDI);
var PageName = new Object();
PageName["mdlPageId"] = getelementId;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageContentHtml"] = tinyMCEcontent;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageName"] = "Default";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlAligen"] = "Central";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlOrderNumberHorizontal"] = "1";
getAttrIDArray.push(PageName);
alert(JSON.stringify(getAttrIDArray));
var contentGetAttrIDArray = SecondMainSendAjax("CMS?handler=Content", getAttrIDArray);
});
});

How to pass objects to a javascript function from HTML href link?

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

javascript variable value as a link

I have a variable and I would like to add a link for its value. This below example only returns the html. How can I make this a clickable link when its returned?
var link = 'new link: <b>Clink Here</font></b>'
This should help you:
var myDiv = document.createElement("div");
var link = 'new link: <b>Clink Here</font></b>'
myDiv.innerHTML = link;
document.body.appendChild(myDiv);
For the id:
myDiv.id = "myLink";
alert(document.getElementById('myLink').innerHTML);
You need a container where the HTML will be placed. If you can use jQuery, this becomes very easy.
<div id="container"></div>
var link = '...';
$('#container').html(link);
Working sample: http://jsfiddle.net/mEjUg/
In jQuery:
$("<div />")
.html('new link: <b>Click Here</b>')
.appendTo("body");

How do I create a link using JavaScript?

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

Categories