HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Using TAGS with <script> on your websites

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptyourwebsiteswithtagsusing

Problem

This function creates a series of links at a desired destination by the usage of a premade tag system.

Usage:

  • createMyTAGS_DATA passes in a single line of all the links as: LinkText;LinkAddress;;



  • createMyTAGS_LOCATION passes the destination to a div,span,... to render the result



Result would be:

LinkText1LinkText2 [...]


Note: each of tag(LinkText;LinkAddress;;) must have more than 10 characters.



click here

function createMyTAGS(createMyTAGS_DATA,createMyTAGS_LOCATION){
try{ var linkTags = createMyTAGS_DATA;
var v1 = createMyTAGS_LOCATION;
while (linkTags !== '' && linkTags.indexOf(";;") > 10){
var linkNew = linkTags.slice(0, linkTags.indexOf(";;"));
var linkText = linkNew.slice(0, linkNew.indexOf(";"));
linkTags = linkTags.replace(linkNew+';;', '');
linkNew = linkNew.replace(linkText+';', '');
linkNew = ''+
linkText+' ';
document.getElementById(v1).innerHTML =
document.getElementById(v1).innerHTML + linkNew;
}
}catch(err){alert('createMyTAGS: '+err.message+
'; - statement('+createMyTAGS_DATA+','+createMyTAGS_LOCATION+')')}
}

Solution

From a once over;

  • Indent your code, it will be easier to read



  • Use lowerCamelCase for your names createMyTAGS -> createMyTags, though personally I would call the function createLinks



  • I would call createMyTAGS_DATA simply s for string or data



  • I would call createMyTAGS_LOCATION either id or element or elementID, you wont then feel the need to assign that parameter to the slightly better named linkTags



  • For your string handling, you should read up on .split(), it would make this so much easier



  • alert statements are terrible, this function should never go wrong. Consider using console.log instead if you must.



  • If you have long variables or chained variables (which you should avoid), consider +=:



document.getElementById(v1).innerHTML = document.getElementById(v1).innerHTML + linkNew;
becomes

document.getElementById(v1).innerHTML += linkNew;

  • Consider using addEventListener instead of assigning the event listener straight into the HTML



My counter proposal:



function createLinks(data, elementId){

var element = document.getElementById(elementId),
links = data.split(';;'),
html = element.innerHTML,
linkParts, url, text;

links.forEach( function( link ){
linkParts = link.split(';');
text = linkParts[0];
url = linkParts[1];
html += ''+text+' ';
});

element.innerHTML = html;
}

click here

Context

StackExchange Code Review Q#70542, answer score: 3

Revisions (0)

No revisions yet.