adding 'target' attribute to an element with pure javascript - javascript

I am trying to add an target="_blank" attribute to an <a> element in my javascript but it's seems like my function disturb the element in some way and won't add it.
note without the function the target="_blank" working fine, only when I add the animation and delay function it's disabling it.
HTML and JS:
var fbId = document.getElementById('fb-id');
fbId.addEventListener('click', function(e) {
fbId.classList.add("animated", "bounceOut");
fbId.setAttribute('target', '_blank');
e.preventDefault();
var fbLink = fbId.href;
setTimeout(function(url) {
window.location = url;
}, 1000, fbLink);
});
<div class="col-3">
<a id="fb-id" href="https://www.facebook.com" target="_blank">
<img class="social-icon" id="fb-icon" src="img/fb.png" alt="facebook">
</a>
</div>

you're using the wrong function - you need to use:
window.open("http://www.google.at", '_blank');
Full Code:
var fbId = document.getElementById('fb-id');
fbId.addEventListener('click', function(e){
fbId.classList.add("animated", "bounceOut");
e.preventDefault();
var fbLink = fbId.href;
setTimeout(function(url) { window.open(url, '_blank'); }, 1000, fbLink);
});
See the working JsFiddle: http://jsfiddle.net/c29u4w7o/43/ which adapts your code so that the window will be opened in a new tab.

Your delay does not delay following the link.
You completely cancel the behaviour of following the link, and then assign a new value to location.
The target attribute is successfully added, but it doesn't get used because the link isn't followed (the browser is navigated via the location assignment instead).
If you want to navigate in a new window using JavaScript, then call window.open() instead of assigning to location.

Related

Cannot change href value of a tag

Im trying to change my href value, but it doesn't seem to be changing at all. I've tried both jQuery and javascript method and neither work.
<a type="button" class="view_me btn btn-primary" href="#">View Full</a>
$(document).on("click", ".click_row", function (e) {
e.preventDefault();
var _self = $(this);
userId = _self.data('id');
var newLink = '/users/view/' + userId //I'd like to eventually use this as new href link
$(".view_me").prop("href", "www.google.com"); // Tried testing with a simple webpage
// document.getElementById('view_test').href = "www.google.com"; // Tried this as well, doesn't work
console.log(newLink)
});
Any suggestion would help. I'm using jQuery 3.2.1
There were a few issues that were impeding the intended behavior. First, your click function wasn't being called because it was looking for the click_row class; I believe you may have meant for this to be the view_me class instead.
Second, you need to add https:// to the beginning of the URL to have it redirect properly. Lastly, you needed to set the href property of the link in your code that had the class view_me, not the id view_me.
EDIT: Also, delete e.preventDefault() or else you can only open the link in a new tab.
The following JS code fixes these issues and produces the desired behavior:
$(document).on("click", ".view_me", function (e) {
//e.preventDefault();
var _self = $(this);
userId = _self.data('id');
var newLink = '/users/view/' + userId
$(".view_me").prop("href", "https://www.google.com");
console.log(newLink);
});
Working JSFiddle: https://jsfiddle.net/2m0297j1/

Adding an onMouseDown attribute equivalent to each anchor's HREF attribute in a class or document

I'm having trouble getting an onMouseDown function that takes each link and copies the original HREF attribute of its respective anchor tag in a page and loads the URL on the down event.
Let's call this function loadURL().
Right now I'm testing the function in-line for each anchor and am having trouble getting different values for each HREF attribute. I would like to make an onLoad function that essentially adds the onMouseDown attribute and loadURL function to every anchor. Here's the JQuery code I have now.
PROBLEM SOLVED, SHOWING INITIAL PROBLEM FOR REFERENCE
Script:
function loadURL()
{
var url = $('a').attr('href');
location.href = url;
}
function mouseDownerURL () {
$('a').attr('onmousedown', 'loadURL()' );
}
HTML
<body onLoad="mouseDownerURL();">
<a onmousedown="" href="foo.com">Takes you to foo.com on mouseDown</a>
<a onmousedown="" href="bar.com">Leads to foo.com NOT bar.com on mouseDown</a>
</body>
SOLUTION
function mouseDownerURL() {
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
}
<body onLoad="mouseDownerURL();">
1
2
...
Get rid of all of those functions and onload things and just do it normally:
$(document).ready(function() {
$('a').mousedown(function() {
windows.location.href = this.href;
});
});
Your problem is this line:
var url = $('a').attr('href');
$('a') selects all of the <a> tags, not the one that was clicked. To work around that, you have to pass the element into your function via an argument, but that's not a great idea.

js iframe close button

I Have the following which opens an iframe with html page loaded, works great, but how to add a close button to the page/iframe so it simply closes the iframe/page and does not affect the page its opened over:
(function (d) {
var modal = document.createElement('iframe');
modal.setAttribute('src', 'mypage.html'));
modal.setAttribute('scrolling', 'no');
modal.className = 'modal';document.body.appendChild(modal);
var c = document.createElement('link');
c.type = 'text/css';
c.rel = 'stylesheet';
c.href = '//myurl.com/testes.css';
document.body.appendChild(c);
}(document));
I tried the following which tried to close it, but, then gives a 404 message inside the iframe:
Close
I am loading jquery on the page if that helps at all, meaning, if there is a jquery solution.
Links are supposed to link somewhere and the href attribute takes a URI.
Use a <button type="button"> and bind a click handler to it. (You could use an onclick attribute, but that wouldn't be unobtrusive)
The unobtrusive approach would be:
foo
And then bind an event handler along the lines of
myLink.addEventListener('click', function (e) {
var d = window.parent.document;
var frame = d.getElementById('myFrame');
frame.parentNode.removeChild(frame);
e.preventDefault();
});
You could put the link into some kind of container div for your iframe, creating the latter with this structure:
<div id="iframe-container">
<a href='#' onclick='this.parentNode.parentNode.removeChild(this.parentNode)'>Close</a>
<iframe src="http://some.web/page.html" />
</div>
Works without any framework.

Best Practice for JS - window.open() in href or in onclick?

Just a question about optimization, between :
link-1
and :
link-2
Is one better than the other ? Or more compatible ? Thanks.
Best practice is to use the target attribute:
link-1
If that doesn't suit, a click handler (ideally not assigned via attribute) would be my take.
Neither one
Make it a regular link using href and target
<a id='my-link' target="_blank" href="http://myUrlBis.com">link-2</a>
If you need to do some processing of the click with JavaScript, you can use the following
document.getElementById("my-link").onclick = function(e) {
// Do some processing here, maybe
window.location = this.href
// Return false to prevent the default action if you did redirect with script
return false;
}
No JavaScript
<a target="_blank" href="myUrlBis.com">link</a>
With JavaScript
<a target="_blank" href="http://www.example.com" id="myLink">link</a>
<script>
document.getElementById("myLink").onclick = function(){ //attach click event to link
var winPop = window.open(this.href); //`this` is reference to link, get href
return false; //prevent click event from clicking the link
}
</script>
JSFiddle Example
Below code should be fine.
<a href="javascript:void(0);" onclick="window.open(url)">
Found issue in IE (version:11) with below code
<a onclick="javascript:window.open(url)">
Problem: The parent window is getting refreshed in IE when we have javascript window.open code in href attribute.

Use HTML/CSS/Javascript to open links in new pages

I have a div that is represented in multiple pages across my site. I don't want to set each one specifically to open in a new window, rather I want all links in that specific div to open in a new window. How can I do this using HTML/ CSS/ javascript?
Thanks
here's how you could do that with jQuery
if you have something like <div class="myLinks">...</div>
$('.myLinks a').attr("target", "_blank");
Well, I guess there are two reasonable ways to open the href from an anchor in a new window.
Edit the node and set its target to _blank ()
Use Javascript to catch the click event, prevent the default behavior and call window.open()
var anchors = document.querySelectorAll('#mydiv a');
[].forEach.call(anchors, function(anchor) {
anchor.addEventListener('click', function(e) {
window.open(e.target.href, 'mywindow', '_blank');
e.preventDefault();
e.stopPropagation();
}, false);
});
That example code is vanilla Javascript and it'll only work in a W3C compliant browser (!= IE).
If you can afford to you use a JS framework live is going to be easier since all of those will abstract browser differences for you.
I think you have a div and link like this in some pages:
<div id="myDiv">
Link Text
<!--some other elements-->
</div>
you need to create a js file like bellow and add it to end of all of your pages :
var div = document.getElementById("myDiv");
if (div) {
for (var i = 0; i < div.childNodes.length; i++)
{
if (div.childNodes[i].nodeName.toLowerCase() == "a")
div.childNodes[i].target = "_blank";
}
}
And its all things you need to do !
this code is fast enough and even does not need JQuery.
Couldn't you use jQuery to iterate through all links within a specified div, then set the target to "_blank".
You can use javascript and jQuery.
First of all I suggest that DIV have id outgoing.
<div id='outgoing'>
<a href='http://google.com'>Go to Google</a><br>
<a href='http://stackoverflow.com'>Look at SO!</a>
</div>
Now we can use simple JavaScript to dynamiclaly add target='blank' into these links:
$(function() {
$('#outgoing a').attr('target', '_blank');
});
You can check example here

Categories