How to disable the hyperlinks in a div - javascript

How can I disable all hyperlinks in a div element? I don't want any active links in my div(editable).

jQuery:
$("#myEditableDiv a").click(function(e){ e.preventDefault(); });
Old and considered bad.
$("#myEditableDiv a").click(function(){ return false; });

using javascript you can write a simple method as given below -
function disableLinksByElement(el) {
if (document.getElementById && document.getElementsByTagName) {
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
var anchors = el.getElementsByTagName('a');
for (var i=0, end=anchors.length; i<end; i++) {
anchors[i].onclick = function() {
return false;
};
}
}
}
//Call to function as
disableLinksByElement('mydiv');

First grab all the links.
var links = editable.getElementsByTagName('a'); // where "editable" is a var pointing to your div
Then set the onclick to false.
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function() { return false; };
}

Related

Set CSS property with pure JS, display:none

I need to hide a <section> in my HTML with JavaScript while highlighting the text or to show it otherwise.
My selection works in this way:
document.addEventListener('click', function(){
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected == '') {
links.setAttribute('style', 'display:block;');
} else {
links.setAttribute('style', 'display:none;');
}
})
but this setAttribute does not work as other hundreds of tries that I have done.
Can someone save my life??
Every setAttribute, style.innerHTML, etc.
when you are selecting links it retuns HTMLCollection forExample : [linkAnnotation1, linkAnnotation2] it not returns one element because your code doesnot works you must write for loop example:
document.addEventListener('click', function () {
var selected = window.getSelection();
var links = document.getElementsByClassName('linkAnnotation')
if (selected == '') {
for (let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:block')
}
}else {
for(let i = 0; i <= links.length - 1; i++) {
links[i].setAttribute('style', 'display:none')
}
}
})
getElementsByClassName returns a HTMLCollection (Which returns an array-like object of all child elements which have all of the given class name(s)). You have to iterate through all of those elements and change properties.
So, you have to use the following code:
document.addEventListener('click', function() {
var selected = window.getSelection();
var links = document.getElementsByClassName("linkAnnotation");
if (selected === '') {
links.forEach(val => { val.setAttribute('style', 'display:block;'); });
} else {
links.forEach(val => { val.setAttribute('style', 'display:none;'); });
}
})

How to compare 2 DOM elements?

I want to alert b if element is $("[id$=linkbuttonabsd]") and alert a otherwise.
JavaScript code:
$("body").find("a").click(function (e) {
var herf = $("body").find("a");
var link = $("[id$=linkbuttonabsd]");
var isb = false;
for (var i = 0; i < herf.length; i++) {
if (herf[i] == link) {
isb = true;
}
}
if (isb) {
alert("b");
} else {
alert("a");
}
});
But I can not achieve this by herf[i] == link. How should it be done?
$.fn.is() can be used.
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
if(herf.eq(i).is(link)){
//Condition is ture
}
Also to get the element at specified index use .eq() rather than []
You don't need to loop through the objects. Code can be reduced to
$("body a").click(function(e) {
var herf = $("body a");
var link = $("[id$=linkbuttonabsd]");
var isb = herf.is(link);
if (isb) {
alert("b");
} else {
alert("a");
}
});
Try using $.is to match an element. Here is the example:
if ($(herf[i]).is("#linkbuttonabsd")) {
isb = true;
}

addEventListener click for Unordered List

Attempting to convert a for loop that steps through an unordered list of hyperlinks adding an 'onclick' function to each into one using an eventlistener for an assignment. I have been unable to get a working model.
Here is the navlist and links I am working with, note that these I cannot edit or change in any way.
<body>
<ul id="navlist">
<li id="l0"> Sniffer </li>
<li id="l1"> is </li>
<li id="l2"> good </li>
<li id="l3"> programmer </li>
</ul>
<script>
var myLinks = [
'http://bing.com/search?q=Sniffer',
'http://bing.com/search?q=is',
'http://bing.com/search?q=good',
'http://bing.com/search?q=programmer'
];
And here is the code sample that I am converting:
window.onload=function() {
for (var i=0; i< myLinks.length; i++) {
// document.getElementById("l"+i).getElementsByTagName("a")[0]).href=myLinks[i];
document.getElementById("l"+i).getElementsByTagName("a")[0].onclick=(function(idx) {
var idx = i;
return function() {
window.location.href = myLinks[idx];
return false; // cancel href
};
})(i);
}
}
</script>
</body>
I have attempted a few different ways of formatting the specific document elements in the concatenation. but none of them work. Here is my most recent and simplest attempt:
window.onload=function() {
for (var i=0; i< myLinks.length; i++) {
document.getElementById("l"+i).addEventListener("click", function() {
var idx = i;
return function() {
window.location.href = myLinks[idx];
return false; // cancel href
};
})(i);
}
}
I very much need help with this as I have tried to work with this code for a decent number of hours. I don't really even understand what the code is doing to be able to convert to a click event.
Thanks in advance.
You can do it this way:
var myLinks = [
'http://bing.com/search?q=Sniffer',
'http://bing.com/search?q=is',
'http://bing.com/search?q=good',
'http://bing.com/search?q=programmer'];
window.onload = function() {
for (var i = 0, len = myLinks.length; i < len; i++) {
document.getElementById("l" + i).addEventListener("click", (function (idx) {
return function () {
window.location.href = myLinks[idx];
return false; // cancel href
};
})(i));
}
};
Event delegation is a nice solution to this problem:
var myLinks = [
'http://bing.com/search?q=Sniffer',
'http://bing.com/search?q=is',
'http://bing.com/search?q=good',
'http://bing.com/search?q=programmer'
];
var list = document.getElementById('list');
list.addEventListener('click', function (event) {
if (event.target && event.target.nodeName === "A") {
event.preventDefault();
var index = Array.prototype.indexOf.call(list.children, event.target.parentNode);
var href = myLinks[index];
console.log('link to ' + href + ' was clicked.');
// window.location = href;
}
});
Fiddle

How to Change All Links with javascript

I want to change all links of my site. Suppose a link given by .Example http://www.google.com/ changes to http://www.mysite.com/?redirect=http://www.google.com/
i have my own redirector just i need to change the links via javascript for all url
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href
}
You can then make the code run on page-load by wrapping it in a function linked to window.onload event:
window.onload = function() {
/* onload code */
}
If you use javascript without a framework, you can use the following lines:
var links, i, le;
links = document.getElementsByTagName('a');
for (i = 0, le = links.length; i < le; i++) {
links[i].href = "http://www.mysite.com/?redirect=" + encodeURIComponent(links[i].href);
}
Just another version with some checks for local links and .forEach()
var links = [].slice.apply(document.getElementsByTagName("a"));
links.forEach(function(link) {
var href = link.href;
if (href.length && href.substring(0, 1) !== "#" && href.substring(0, 1) !== "/") {
link.href = "http://www.mysite.com/?redirect=" + encodeURIComponent(link.href);
console.log(link.href);
}
});
$('a').each(function(i, e)
{
var current = $(this);
current.attr('href', 'http://www.mysite.com/?redirect=' + encodeURIComponent(current.attr('href')))
});

expanding and collapsing folders

I need to get more than one element to toggle open and closed. Right now the function is just selecting the ID, but I'd like to know how to get it to select a class. I thought I could change the document.getElementById to document.getElementByClass but that didn't work.
I picked this bit of code during my search:
#ToggleTarget {display:hidden;}
<script type="text/javascript">
function Toggle() {
var el = document.getElementById("ToggleTarget");
if (el.style.display == "block") {
el.style.display = "none";
}
else {
el.style.display = "block";
}
}
</script>
var getElementsByClassName = function(node, classname) {
if (document.getElementsByClassName) {
return document.getElementsByClassName(classname);
}
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
var Toggle = function(){
var tp = getElementsByClassName(document.documentElement,'toggle');
for(var i = 0; i < tp.length; i++){
if(tp[i].style.display=='none')
tp[i].style.display='block'
else
tp[i].style.display='none'
}
}
Use getElementsByClassName and then loop through them.
EDIT
Just make sure they have the class toggle as used in my code above.
UPDATE
Added function for IE support (adopted from https://stackoverflow.com/a/7410966/600101).

Categories