javascript unobtrusive - javascript

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...

With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});

I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>

What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/

Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)

I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.

// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

Related

How can set the title of all the links in a page

I would like to make some javascript code that once run adds a title of each link that is the title of the page it leads to. Sorry, all I can figure out is...
<body onload="replace()">
<script>
function replace() {
document.getElementsByTagName("a").title=this.href;
}
</script>
hi
hi2
hi3
</body>
But nothing happens and I can't figure it out.
more simple, just place correctly your script:
<body>
hi
hi2
hi3
<!-- Script for everything, just placed before </body>-->
<script>
document.querySelectorAll('a').forEach(A=>{ A.title = A.href })
</script>
</body>
getElementsByTagName returns a collection of elements, you need to use loop for setting whatever to each link.
<body onload="replace()">
<script>
function replace() {
// find all links
var links = document.getElementsByTagName("a");
// loop the collection and set title to each one
for (var i = 0; i < links.length; i++) {
links[i].title = links[i].href;
}
}
</script>
hi
hi2
hi3
</body>
Afaik, there is no way to detect a page title from a different page in JS. If you know the titles in advance, you can create a mapping object and loop over your links like so:
var map = [['link','title'],['link','title']];
$('a').each(function() {
for(var i=0; i<map.length; i++) {
if(map[i][0] == $(this).attr('src'))
$(this).attr('title', map[i][1]);
}
});
That should set all your links with the appropriate page titles based on matching the src attributes of each link against the link in your mapping object
You can use window.location.href instead of this.href. Also, you probably need to run through each link in the tag list:
function start() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].title = window.location.href;
}
}
window.load = start();
hi
hi2
hi3
Try this answer, I have tried to add comments so that you could understand what has happened:
<a class="link" href="about.html">About</a>
<a class="link" href="careers.html">Careers</a>
<a class="link" href="contact.html">Contact</a>
<script>
//create a true array
var links = Array.from(document.getElementsByTagName("a"));
window.addEventListener(
"load", //Trigger Load event of window object
()=> //return this function
{
//links is an array of a-tag objects
for (let i = 0; i < links.length; i++)
{
//for each a tag object
//set the attribute targeted below
links[i].setAttribute
(
//target the title attribute
"title",
//set it to the current href attribute value of the that a-tag object
links[i].getAttribute("href")
);
}
}
);
</script>

Multiple Class Names - getelementsbyclassname

Basically I want a logo to change, there are 2 current logos, individually labelled with the classes... 'Header-branding-logo' & 'Mobile-bar-branding-logo'. I can change either one of them, but not at both at the same time.
I can't seem to figure out where I need to put it. Can anyone help?
<script>
window.onload = function() {
document.getElementsByClassName('Header-branding-logo')[0].src = 'https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/1522872070340/GBL+Shop+-+Black+1500.png';
};
</script>
UPDATE
Thanks to the genius below, this now works for me
<script>
window.onload = function() {
var elements = document.querySelectorAll('.Header-branding-logo,.Mobile-bar-branding-logo');
elements.forEach((element) => {
element.src = "https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/1522872070340/GBL+Shop+-+Black+1500.png"
})
};
</script>
Please use the querySelectorAll function
var elements = document.querySelectorAll('.Header-branding-logo,.Mobile-bar-branding-logo');
elements.forEach((element) => {
element.src = "https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/1522872070340/GBL+Shop+-+Black+1500.png"
})
<script>
window.onload = function() {
var classes = document.querySelectorAll(".Header-branding-logo, .Mobile-bar-branding-logo") // Gets multiple classes whereas getElementsByClassName() fetches only one. Also dont miss the '.' before classnames here
for(i = 0; i <= classes.length; i++){
classes[i].src = "https://static1.squarespace.com/static/5a9e8da0aa49a18379207907/t/5ac52f062b6a28a603df30cf/1522872070340/GBL+Shop+-+Black+1500.png"
}
}

Inserting CSS-linked HTML in HTML page code via JS

I do not have access to the HTML of the pages (they are program-built dynamically).
I do have access to the JS page it is linked to.
For example I can do somethin like this and it works:
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
while(i<=1)
{ if(!document.getElementById('timedrpact01'+i))
{
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
output.appendChild(ele);
I would like to use this basis insert a button that would allow to switch from one CSS set (there are several files invoked) to another _another path.
Many thanks
The external stylesheets are referenced using link, as in:
<link rel="stylesheet" href="http://example.com/path-to-css">
So, get hold of the appropriate link element using:
var css = document.getElementsByTagName("link")[0];
Here, we got hold of the first link available by specifying the [0] index.
Then, overwrite the href attribute to point it to the new path.
css.setAttribute("href", "http://example.com/path-to-css");
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
//switch all the href's to another path
var switchStyleSheet = function() {
var links = document.getElementsByTagName("link");
for(var i=0; lkC = links.length; i < lkC; i++)
links[0].href = links[0].href.replace('path_to_file', '_path_to_file');
};
while(i<=1) //while is not required here, if i is 1
{
if(!document.getElementById('timedrpact01'+i)) {
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
var button = document.createElement('button');
if(button.addEventListener) {
button.addEventListener('click', switchStyleSheet);
}
else {
button.attachEvent('click', switchStyleSheet);
}
output.appendChild(button);
output.appendChild(ele);
}
}
}

Remove onclick event from img tag

Heres my code:
<div id="cmdt_1_1d" class="dt_state1" onclick="sel_test(this.id)">
<img id="cmdt_1_1i" onclick="dropit('cmdt_1_1');" src="/site/hitechpackaging/images/items/bags_menu.jpg ">
<span class="dt_link">
BAGS
</span>
</div>
Unfortunately I cannot modify this file, is there a way using javascript to disable the onclick from the img tag only.
I was using this script but it disable the onclick event from all images. But i want only from this component
var anchorElements = document.getElementsByTagName('img');
// for (var i in anchorElements)
// anchorElements[i].onclick = function() {
// alert(this.id);
// return false;
// }
Any ideas will be appreciated.
Edited:
Is there a way to stop the function dropit from executing, is it possible using javascript. On page load, etc.
another option is can i rename the img file using javascript??
document.getElementById('cmdt_1_1i').removeAttribute("onclick");
var eles = document.getElementById('cmdt_1_1d').getElementsByTagName('img');
for (var i=0; i < eles.length; i++)
eles[i].onclick = function() {
return false;
}
Lots of answers, but the simplest is:
document.getElementById('cmdt_1_1i').onclick = '';
try something like this:
var badImage = document.getElementById("cmdt_1_1i");
badImage.onclick = null;
badImage.addEventlistener("click",function(e){
e.preventDefault();
e.stopPropagation();
return null;
},true);
If you later need to restore the onclick property, you can save it in a field before overwriting it:
document.getElementById(id).saved=document.getElementById(id).onclick;
document.getElementById(id).onclick = '';
so that later you can restore it:
document.getElementById(id).onclick=document.getElementById(id).saved;
This can be useful especially in the case, in which the original onclick property contained some dynamically computed value.
You can programmatically reassign event listeners. So in this case, it might look something like:
const images = document.querySelectorAll('#cmdt_1_1d img')
for (let i = 0; i < images.length; i++) {
images[i].onclick = function() => {}
}
...where the query above returns all of the img tags that are descendants of the element with ID cmdt_1_1d, and reassigns each of their onclick listeners to an empty function. Therefore no actions will take place when those images are clicked.

Editing all external links with javascript

How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?
I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).
But, how do I do this in code?
This one is tested:
<style type="text/css">
.AddedClass
{
background-color: #88FF99;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var re = /^(https?:\/\/[^\/]+).*$/;
var currentHref = window.location.href.replace(re, '$1');
var reLocal = new RegExp('^' + currentHref.replace(/\./, '\\.'));
var linksDiv = document.getElementById("Links");
if (linksDiv == null) return;
var links = linksDiv.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var href = links[i].href;
if (href == '' || reLocal.test(href) || !/^http/.test(href))
continue;
if (links[i].className != undefined)
{
links[i].className += ' AddedClass';
}
else
{
links[i].className = 'AddedClass';
}
if (links[i].title != undefined && links[i].title != '')
{
links[i].title += ' (outside link)';
}
else
{
links[i].title = 'Outside link';
}
}
}
</script>
<div id="Links">
<a name="_Links"></a>
FOO
FILE
SomeWhere
SomeWhere 2
SomeWhere 3
ElseWhere 1
ElseWhere 2
ElseWhere 3
BAR
Show/Hide
</div>
If you are on an account on a shared server, like http://big-server.com/~UserName/, you might want to hard-code the URL to go beyond the top level. On the other hand, you might want to alter the RE if you want http://foo.my-server.com and http://bar.my-server.com marked as local.
[UPDATE] Improved robustness after good remarks...
I don't highlight FTP or other protocols, they probably deserve a distinct routine.
I think something like this could be a starting point:
var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
if (links[i].href.substring(0, 5) == 'https')
{
links[i].setAttribute('title', 'abc');
links[i].setAttribute('class', 'abc');
links[i].setAttribute('className', 'abc');
}
}
you could also loop through all the A elements in the document, and check the parent to see if the div is the one you are looking for
This can be accomplished pretty easily with Jquery. You would add this to the onload:
$("div a[href^='http']").each(function() {
$(this).attr("alt",altText);
var oldClassAttributeValue = $(this).attr("class");
if(!oldClassAttributeValue) {
$(this).attr("class",newClassAttributeValue);
}
});
You could modify this to add text. Class can also be modified using the css function.
My (non-framework) approach would be something along the lines of:
window.onload = function(){
targetDiv = document.getElementById("divName");
linksArray = targetDiv.getElementsByTagName("a");
for(i=0;i=linksArray.length;i++){
thisLink = linksArray[i].href;
if(thisLink.substring(4,0) = "http"){
linksArray[i].className += "yourcontent"; //you said append so +=
linksArray[i].alt += "yourcontent";
}
}
}
This is not tested but I would start like this and debug it from here.

Categories