Javascript Open all links on _blank Except - javascript

I am using this code below to open all links on _blank pages and it works great!
I just have one problem.
How can I make it so a specific link or class is ignored by the script?
Here's the code:
<script>
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
window.open(element.href, "_blank", "location=yes");
return false; // prevent default action and stop event propagation
}
};
</script>

To ignore specific classes, use the below:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A' && !element.classList.contains('noBlank')) {
window.open(element.href, "_blank", "location=yes");
return false; // prevent default action and stop event propagation
}
};
<p>BBC should not be _blank</p>
Google
<br />
Yahoo
<br />
<a class="noBlank" href="http://www.bbc.co.uk">BBC</a>

Related

Javascript interrupt normal behavior on link click momentarily

I want to do something before my page unloads so I'm trying to interrupt normal behaviour momentarily. I tried this but it doesn't seem to work:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `a`) {
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
return true; // return false = prevent default action and stop event propagation
}, 500);
}
}
0.5s is the time I need to display a short css animation before leaving the page.
You can try the following code:
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == `A`) { // !uppercased
e.preventDefault(); // prevent default anchor behavior
var goTo = element.href; // store target url
document.body.classList.remove(`ready`);
document.body.classList.add(`leaving`);
setTimeout(function () {
window.location = goTo; // navigate to destination
}, 500);
}
}

Detect Ctrl + click in event handler

I want to replace detecting a double-click with detecting Ctrl-click, but I do not know how to do so.
$(document).ready(function () {
$(document).dblclick(function (e) {
var target = (e && e.target) || (event && event.srcElement);
var tag = target.tagName.toLowerCase();
if (!(tag == 'input' || tag == 'textarea' || tag == 'img')) {
openIfSelected("dblclick");
}
});
});
You are looking for the jQuery .click() method and the MouseEvent.ctrlKey property.
You could do something like:
$(document).ready(function () {
$(document).click(function (e) {
if(e.ctrlKey){
var tag = e.target.tagName.toLowerCase();
if (!(tag == 'input' || tag == 'textarea' || tag == 'img')) {
openIfSelected("dblclick"); //Still pass "dblclick", but upon Ctrl-click
}
}
});
});
function openIfSelected(reason){
//This is now only called upon Ctrl-click, but the "reason" remains "dblclick".
console.log('Called "openIfSelected" with reason: ' + reason);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><kbd>Ctrl</kbd>-Click me</div>
Note:
You used the code:
var target = (e && e.target) || (event && event.srcElement);
This is strange as written. You were probably attempting to use window.event. However, this is not needed because you are using jQuery, which normalizes the event object that is passed to event handlers, specifically so you don't have to do things like this. In addition, the tags you are using declare this question as a Google Chrome extension issue. If that is the case, and you weren't using jQuery, then you would still not need to do this as you do not need to account for the use of the code in older browsers (e.g. IE).
I fixed like this. Big thanks Makyen.
$(document).ready(function () {
$(document).click(function (e) {
if(event.ctrlKey){
var target = event.srcElement;
var tag = target.tagName.toLowerCase();
if (!(tag == 'input' || tag == 'textarea' || tag == 'img')) {
openIfSelected("dblclick");
}
}
});
});

JavaScript Link Element over Image

I am trying to intercept all a link clicks to do some extra work and this works fine for standalone a links but when it contains an img for example the img tag is returned instead.
JSFiddle
Is there a way to check if the element above is also an a link or is there a different way I should be handling this?
JS :
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A') {
window.open(element.href, "_system");
return false;
}
};
you can traverse up the parent of the clicked node to see if an ancestor is an A tag
...
var element = e.target || e.srcElement;
while (element.tagName != 'A' && element.parentNode) {
element = element.parentNode;
}
if (element.tagName == 'A') {
...
You can attach the handler on the click event of the anchor tags instead of on the whole document, then you will not need to check for the event target.
var anchorTags = document.getElementsByClassName("classname");
var myEventHandler = function() {
// stuff
};
for (var i = 0; i < anchorTags.length; i++) {
anchorTags[i].onclick = myEventHandler;
}
I'm not sure if you need to actually capture all clicks, but if you're looking to capture the anchor tag that was actually clicked, you might consider the approach below.
var anchors = document.getElementsByTagName('a');
for(var i = 0, anchor; anchor = anchors[i]; i++ ) {
anchor.addEventListener('click', function (e){
e = e || window.event;
//Grabs the element that initiated the event, the anchor tag.
var element = this;
alert(element.tagName);
if (element.tagName == 'A') {
window.open(element.href, "_system");
return false;
}
})
}
You should add another condition to check if the current clicked element is a child of a element.
You could use closest method.
The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null.
The condition will be like following :
if (element.tagName == 'A' || element.closest('a') != null) {
window.open(element.closest('a').href, "_system"); //Using the parent a link `href`
return false;
}
Hope this helps.
document.onclick = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
if (element.tagName == 'A' || element.closest('a') != null) {
alert("Open with href :"+element.closest('a').href);
return false;
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>The below Google text link returns A when clicked, correct!</p>
Google Link
<br />
<p>The below Bing image link returns IMG when clicked, incorrect!</p>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALAAAABOCAMAAAC38WwFAAAAwFBMVEX///8Adb4Acr0AcLwAbrsAd7+dxeMAb7zS5fMAe8H7qClfnc/p9Prc7Pa72e0dfsJIk8sxishqrNj0+/0Aa7qPuNxWlcvZ5PHZ6/YAabno8/pvqNXw9/u+1Op/tNtAi8ipzue11evL4PCZvd77pRtYn9GDud4Vg8Wl0Olgp9ZJmM6TweGIsdjE3O6pyORmoNF5qtYpjcn8s0T/+/X8xXj93rP/9en8v1/916T+7tj+6c38uVH7rzGIs9r90JP7ogvMNc9SAAAGjklEQVRoge2aa2OiOBSGJYRblZuoVbQoVKTKgjqd2dnZnXb+/79aMCdclICXavvB91ORJOdJcnJyEtpq3XXXXXfdddddd32I1Med7FPqvP747/fD7+//vl4LqkadwaiXaPR2Qp1fP+fzh4eH+cP7JxB32jyXCPWPr/L6PcVNNf9xPTCWzgD++4Fq/vN6YCydA/wtA/5+PTCWzgBu/QMuMf/262pcTJ0D/Prj95/5fP7n579Xw2LrHOAU+f39/YrDa2mh010uvYpXh8D2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i8VY4K0rkwK0+mSlOig8terDN43VNkIV8g2twYpoD7Mfhk4Etn+a94z2Tdl+HTcGs28XcEZDUWvToTO7vdCcDtzprmmDqywKy6pgcmWzc0BgkobXJD50rAnYZcJJg6zSB6Sl+6HqeJi6DngRZt95v2HTlAALFjFlkCLycsAv4FwInsaDN0SQaJUf8Xg9n5z993Riv6JkFMbvmwoKjs3AxcMuerXLGksyXRt6cmKvMqi1HoIcwMHg5cNKqvEzvJXiUCYgP7wQqlMQs8Hc/skvDbNmiAKs6P4R9BHCqjrsYt41pImOwHtAQjANmopHLdmAdJMf8cfwUyaqdSPXiTUBxcX5k+yjgnSx6PnY39PCnNO5iSbXIH9GLFF4Jki4nMgIkUW/Yxnm+96HABQYNlj/imOlysbi3Kl5V5X6V3sGYs6JjFW9+NCX9U2rKh3cVcD1wkjtuYXym9c1RDZ0puc0rXHvxgjlw9tLt2XQnP12iXjudi8Gm/oS12hUa1IV6QryCYHzsVy3VjfvZfakebNub55l3EOwmw53IHZFFVN/uUYVSwQ7V5GIldeBCOr2S7hxh42O1OfbI9lUEp2Z82jeMTxQ9kixP/lbxSfIAuCk//zJyCTA/vvnqOVN9yLufPxuESoUIxJhxm14WNieZN9ICNqVF9WsRtqw284L41hpCKlt9HUhPYsIRCdut9EK/8lRk6jIcROoum2+vLv1M0y2fmi05BF7kfxJatSyHox953jS69ibybEOTS7T5YjHYEuErIuKDwdgJw3CxHpgCPTVz7G8tn6bOSsg/1haPdAgJxkn/4HUzRWNTOjg1Ixysv1B4KMuSY1/HuHBWwILRj76Y95Y1Ub2FH+BRop5udF31azrDoSzrS4/rXXfdddcV9D+HE313nFHd7gAAAABJRU5ErkJggg==" />
</body>

how to capture "ESC" from an iframe?

i need to capture esc key to close my open div.The div contents an iframe. it's works when i open the div and soon press esc to close it.But when i clicked the iframe,and pressed key esc,it's no more work for me.becuse it only capture the current window(at this point will be the iframe window),how can i fix it ?
Here is my parent window's code:
window.onkeydown = function(e) {
var e = e || window.event;
if (e.keyCode === 27) {
_this.closeDemo();
}
}
How about adding a onkeydown handler inside the iframe:
window.onkeydown = function(e) {
var e = e || window.event;
if (e.keyCode === 27) {
parent.closeDemo();
}
}

On click of textbox event getting bubbled

This is my HTML structure.
<div id="dvHirearachy" class="MarginTB10">
<span>
<label>Hierarchy Names</label><br />
<input type="text" name="txtHierarchy" />
<a id="ancRemove" href="#">Remove</a>
</span><br />
<a id="ancNew" href="#">New Hierarchy Name</a>
</div>
On click of anchor tag "ancNew" , I am generating again the complete span tag above mentioned in the markup.
The problem is on click of textbox also the span structure is getting generated. Same problem i was facing on click of "ancRemove" for that i tried to stop the event bubbling, it has worked for this but not for the textbox.
my script.
$(document).ready(function () {
$("#ancRemove").click(function (e) {
RemoveHierarchy(this, e);
});
$("#ancNew").click(function (e) {
generateNewHierarchy(e);
});
});
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
$(container).append("<br/>").prependTo("#ancNew");
$(container).children('input[type=text]').focus();
}
}
function createElements(elem,type) {
var newElem = document.createElement(elem);
if (type != null) {
newElem.type = "input";
newElem.name = "txtHierarchy";
$(newElem).addClass('width_medium');
}
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).click(function (e) {
RemoveHierarchy(this,e);
});
}
return newElem;
}
function RemoveHierarchy(crntElem, e) {
e.stopPropagation();
$(crntElem).parents("span:first").remove();
}
what is the way to avoid the situation.
Check this jsfiddle :
http://jsfiddle.net/xemhK/
Issue is prepandTo statement, It is prepading the elements in #ancNew anchor tag, thats why all textbox and remove anchor, are propagating click event of #ancNew, and it is calling generateNewHierarchy() function.
Change in $(container).append("<br/>").prepandTo("#ancNew"); to $(container).append("<br/>").insertBefore("#ancNew");
function generateNewHierarchy(e) {
if (window.event) {
var e = window.event;
e.cancelBubble = true;
} else {
e.preventDefault();
e.stopPropagation();
var container = createElements('span', null);
$(container).append(createElements('input', 'text'));
$(container).append(createElements('a', null));
//$(container).append("<br/>").prepandTo("#ancNew");
$(container).append("<br/>").insertBefore("#ancNew");
$(container).children('input[type=text]').focus();
}
}
and in createElements
if (elem == "a") {
newElem.innerHTML = "Remove";
$(newElem).attr("href","#").click(function (e) {
RemoveHierarchy(this,e);
});
}

Categories

Resources