Slimming down javascript code....Dynamic header on a static page with javascript - javascript

This element loads last and with delay on the page...
I've created a dynamic header with an external javascript file for my static html page.
I need help slimming down the code.
Also, to call the function, I call the body onLoad method. Any suggestions on how to call this EXTERNAL function before ALL the contents of the page loads?
function addHeaders(){
var emptyHTML = document.getElementById("category_header").innerHTML;
var addHTML =
"<span>" + emptyHTML + "<a href='/broadcast_webcast/' class='catnav'>" + "Live Broadcasts & Webcasts" + "</a>" + "</span>"
+ "<span>" + "<a href='/business/' class='catnav'>" + "Business" + "</a>" + "</span>"
+ "<span>" + "<a href='/celebrities/' class='catnav'>" + "Celebrities" + "</a>" + "</span>"
+ "<span>" + "<a href='/culture/' class='catnav'>" + "Culture" + "</a>" + "</span>"
+ "<span>" + "<a href='/education/' class='catnav'>" + "Education" + "</a>" + "</span>"
+ "<span>" + "<a href='/energy/' class='catnav'>" + "Energy" + "</a>" + "</span>"
+ "<span>" + "<a href='/entertainment/' class='catnav'>" + "Entertainment" + "</a>" + "</span>"
+ "<span>" + "<a href='/environment/' class='catnav'>" + "Environment" + "</a>" + "</span>"
+ "<span>" + "<a href='/fashion/' class='catnav'>" + "Fashion" + "</a>" + "</span>"
+ "<br>"
+ "<span>" + "<a href='/health/' class='catnav'>" + "Health & Fitness" + "</a>" + "</span>"
+ "<span>" + "<a href='/humanitarian/' class='catnav'>" + "Humanitarian" + "</a>" + "</span>"
+ "<span>" + "<a href='/movies/' class='catnav'>" + "Movies" + "</a>" + "</span>"
+ "<span>" + "<a href='/music/' class='catnav'>" + "Music" + "</a>" + "</span>"
+ "<span>" + "<a href='/hollywood/' class='catnav'>" + "Hollywood" + "</a>" + "</span>"
+ "<span>" + "<a href='/newyork/' class='catnav'>" + "New York City" + "</a>" + "</span>"
+ "<span>" + "<a href='/scienceandtech/' class='catnav'>" + "Science & Technology" + "</a>" + "</span>"
+ "<span>" + "<a href='/sports/' class='catnav'>" + "Sports" + "</a>" + "</span>"
+ "<span>" + "<a href='/videogames/' class='catnav'>"+ "Video Games" + "</a>" + "</span>"
document.getElementById("category_header").innerHTML = addHTML;
var getNav = document.getElementById("navtop").innerHTML;
var createNav =
"<span class='navtop'>" + getNav + "<a href='../' class='navtop'>" + "Home" + "</a>" + "</span>"
+ "<span class='navtop'>" + "<a href='/contact-us' class='navtop'>" + "Contact Us" + "</a>" + "</span>"
+ "<span class='navtop'>" + "<a href='/our-expertise' class='navtop'>" + "Our Expertise" + "</a>" + "</span>"
+ "<span class='navtop'>" + "<a href='/worldwide-studios-offices/' class='navtop'>" + "Bader TV Worldwide Studios & Offices" + "</a>" + "</span>"
+ "<span class='navtop'>" + "<a href='/careers' class='navtop'>" + "Careers" + "</a>" + "</span>"
+ "<span class='navtop'>" + "<a href='/urgent-video-requests' class='navtop'>" + "Urgent video Requests" + "</a>" + "</span>"
document.getElementById("navtop").innerHTML = createNav;
}
ref: [badertv.com]

Step 1: Reduce Duplication (make a function which makes the span and a tags give a url and text.
Step 2: Use an array and loop for url and text.
function makeLink(url, text){
return "<span><a href='"+url+"' class='catnav'>"+text+"</a></span>";
}
var url = ['/business/','/celebrities/',...];
var text = ['Business','Celebrities',...];
var out = '';
for(var i = 0; i < url.length; i++){
out += makeLink(url[i],text[i]);
}
add any special cases and you're all set.

In both addHTML and createNav you have only one dynamic variable. Why the concatenation?
Addition:
You can just put the whole thing in a function and call it at after you close the parent tag for the element that will hold the content (you can set two function if the two strings are not for the same container).

The slimming down I guess could go like this, it will spare you a few bytes but I wonder if it is worth the effort. For the loading part: calling this in body onload is safe because it probably guarantees that the getElementbyId will work. If you put a script tag near the end of the </body> tag it might work also but on different browser the behavior might be different (aka broken).
function link(linkText) {
return "<span><a href='/" + linkText[0] + "/' class='catnav'>" + linkText[1] + "</a></span>";
}
function addHeaders(){
var emptyHTML = document.getElementById("category_header").innerHTML,
linkTexts = [
["broadcast_webcast", "Live Broadcasts & Webcasts"],
["business", "Business"]
// etc
],
addHtml;
addHtml = new [];
for (i=0;i<linkTexts.length;i += 1) {
addHtml.push(link(linkTexts[i]));
}
document.getElementById("category_header").innerHTML = addHtml.join("");
// rest of the code
}

Related

how to pass variable inside html href in the view in mvc

i want to pass dynamic imei number , instead of static imei. i want to pass
obj[i].DeviceImei
inside the href tag at the place of 1009 for the google map marker info window view more option.
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
"</div>" +
'<div id="bodyContent">' +
"<p><b>Location: " + obj[i].location + "<br>"
+ "\n" +"IMEI: " + obj[i].DeviceImei +"<br>"
+ "\n" + "PRV Trip: " + obj[i].PRV_T + "<br>"
+'<a href="http://hostname/1009">' +
"View More" +
"</p>" +
"</div>" +
"</div>";
You can scape quotes with \", so in your case it would be:
+'<a href=\"http://hostname/' + obj[i].PRV_T + '\">' +

Search for text inside all child of a div and hide the ones that doesn't contain it

I would like to hide all the divs that doesn't contain the text i'm writing inside a .
i've tried with something like this:
var $searchBox = $('#search-weeazer');
$searchBox.on('input', function() {
var scope = this;
var $userDivs = $('.information ');
if (!scope.value || scope.value === '') {
$userDivs.show();
return;
}
$userDivs.each(function(i, div) {
$('div:contains(scope.value)').hide();
})
});
but doesn't work (i know i will hide the div that contains the text, was for testing purpose ^^)
The divs are created dynamically after an Ajax Call, and the structure of the div is this:
"<div class=\"row information text-white shadow-lg p-2 mb-2\">" +
"<div class=\"col-3 profilePicture\">" +
"<img src=\"../../img/bg-masthead.jpg\" alt=\"Immagine profilo\" class=\"profileImage rounded-circle\">" +
"<div class=\"results\">" +
"<div class=\"results-content\">" +
"<span class=\"stars\">3</span>" +
"</div>" +
"</div>" +
"</div>" +
"<div class=\"col-9 infos\">" +
"<div class=\"row\">" +
"<div class=\"col-4 nome\"><b>Nome: </b>" + nome + "</div>" +
"<div class=\"col-4 regione\"><b>Regione: </b>" + regione + "</div>" +
"<div class=\"col-4 citta\"><b>Città: </b>" + citta + "</div>" +
"</div>" +
"<div class=\"row\">" +
"<div class=\"col-4 dataNascita\"><b>Data di nascita: </b>" + eta + "</div>" +
"<div class=\"col-4 coaching\"><b>Coaching online: </b>" + (coaching === "T" ? "Sì" : "No") + "</div>" +
"<div class=\"col-4 sesso\"><b>Sesso: </b>" + (sesso === "F" ? "Femmina" : "Maschio") + "</div>" +
"</div>" +
"<div class=\"row border-bottom\">" +
"<div class=\"col-6 blurry-text cellulare\"><b>Cellulare: </b>" + cellulare + "</div>" +
"<div class=\"col-6 blurry-text email\"><b>Email: </b>" + email + "</div>" +
"</div>" +
"<div class=\"row descriptionText \">" +
"<div class='col-10 descrizione'>" + descrizione + "</div>" +
"<div class='col-2 align-items-center'><button type='button' class='btn btn-primary btn-large profileButton' data-id='" + id + "'>Profilo</button></div>" +
"</div>" +
"</div>" +
"</div>"
But the script just does nothing for now. Any suggestion?
Currently, you're searching for elements that contain the literal string (scope.value). Use concatenation like so:
$("div:contains('" + scope.value + "')");
Or use a template literal:
$(`div:contains('${scope.value}')`);
$('div:contains(scope.value)')
Should be...
$('div:contains("'+ scope.value +'")')
So the value is appended to the string. Keep in mind if the value can contain double quotes you would have to escape them.

AppenChild dynamic h3 to dynamic div issue

I try to insert a dynamic h3 to a dynamic div, hovewer something is odd as it gets inserted outside the lblUser div. I would also like to be inserted after the "Role" h3.
Here is my code : function showUsers() {
lblUserList.innerHTML = "";
for ( var i = 0; i < ajUserDataFromServer.length; i++ ) {
var lblUser = document.createElement('div');
lblUser.innerHTML = '<div class="lblUser">' + '<img src="' + ajUserDataFromServer[i].image + '" alt="user" class="lblUserImage" data-userImage="' + ajUserDataFromServer[i].image + '">' + '<h3 class="lblUserId">' + 'Id:' + ' ' + ajUserDataFromServer[i].id + '</h3>' + '<h3 class="lblUserRole" data-userRole="' + ajUserDataFromServer[i].role + '">' + 'Role:' + ' ' + ajUserDataFromServer[i].role + '</h3>' + '<h3 class="lblUserName" data-userName="' + ajUserDataFromServer[i].name + '">' + 'Name:' + ' ' + ajUserDataFromServer[i].name + '<h3 class ="lblUserLastName" data-userLastName="' + ajUserDataFromServer[i].lastname + '">' + 'Lastname:' + ' ' + ajUserDataFromServer[i].lastname + '</h3>' + '<h3 class="lblUserPassword" data-userPassword="' + ajUserDataFromServer[i].password + '">' + 'Password:' + ' ' + ajUserDataFromServer[i].password + '</h3>' + '<button id="btnEditUserBody" class="btnShowPage btnEditUser" data-userId="' + ajUserDataFromServer[i].id + '" data-showThisPage="pageUpdateUser">' + 'EDIT USER' + '</button>' + '<button class="btnDeleteUser" data-userId="' + ajUserDataFromServer[i].id + '" >' + 'DELETE USER' + '</button>' + '<h3 class="lblErrorMessage" id="lblDeleteUserErrorMessage">' + '</h3>' + '</div>';
if ( ajUserDataFromServer[i].email ) {
var lblUserEmail = document.createElement('h3');
lblUserEmail.innerHTML = '<h3 class="lblUserEmail" data-userEmail="' + ajUserDataFromServer[i].email + '">' + 'Email:' + ' ' + ajUserDataFromServer[i].email + '</h3>';
lblUser.appendChild( lblUserEmail );
}
if ( ajUserDataFromServer[i].phonenumber ) {
var lblUserPhoneNumber = document.createElement('h3');
lblUserPhoneNumber.innerHTML = '<h3 class="lblUserPhoneNumber" data-userPhoneNumber="' + ajUserDataFromServer[i].phonenumber + '">' + 'Phone-number:' + ' ' + ajUserDataFromServer[i].phonenumber + '</h3>';
lblUser.appendChild( lblUserPhoneNumber );
}
lblUserList.appendChild( lblUser );
}
}
I can see a few things wrong with the code, for example:
var lblUserEmail = document.createElement('h3');
lblUserEmail.innerHTML = '<h3 class="lblUserEmail" data-userEmail="' + ajUserDataFromServer[i].email + '">' + 'Email:' + ' ' + ajUserDataFromServer[i].email + '</h3>';
Should be something like:
var lblUserEmail = document.createElement('h3');
lblUserEmail.classList.add("lblUserEmail");
lblUserEmail.setAttribute("data-userEmail", ajUserDataFromServer[i].email);
lblUserEmail.innerText = 'Email:' + ' ' + ajUserDataFromServer[i].email;
Now you can append it:
lblUser.appendChild(lblUserEmail);
If you do it your way you wil get nested h3 and div elements.
Furthermore, you need to close your img tag. I can advice creating those tags either in code or with the new es5 string interpolation this will clean up your code and will show you these types of errors.

How can this be modified to show 2 videos?

I found this code online that will show the most recent video from a Vimeo account...
$(function() {
$.getJSON('http://vimeo.com/api/v2/VIMEO-ACCOUNT-NAME/videos.json?callback=?', {format: "json"}, function(videoList) {
$.getJSON('http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/' + videoList[0].id + '&byline=false&portrait=false&callback=?', {format: "json"},
function(videoProperties) {
document.getElementById("vimeoRecent").innerHTML=videoProperties.html
document.getElementById("vimeoDescription").innerHTML="<p><a href='" + videoList[0].url + "'>" + videoProperties.title + "</a> from <a href='" + videoProperties.author_url + "'>" + videoProperties.author_name + "</a> on <a href='http://vimeo.com'>Vimeo</a>.</p><p>" + videoProperties.description + "</p>"
});
});
});
I'm trying to figure out how to get it to display the 2 most recent videos, instead of one. I tried to add another item to the array e.g. [0,1], but that just breaks the script.
Can anyone suggest how I could get this script to display 2 videos? Thanks!
Here's a non-functioning jsfiddle just to show the code more clearly.
You need to repeat the second getJSON for the second element using videoList[1].id, and inserting it into other divs
$(function() {
$.getJSON('http://vimeo.com/api/v2/VIMEO-ACCOUNT-NAME/videos.json?callback=?', {format: "json"}, function(videoList) {
$.getJSON('http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/' + videoList[0].id + '&byline=false&portrait=false&callback=?', {format: "json"},
function(videoProperties) {
document.getElementById("vimeoRecent").innerHTML=videoProperties.html
document.getElementById("vimeoDescription").innerHTML="<p><a href='" + videoList[0].url + "'>" + videoProperties.title + "</a> from <a href='" + videoProperties.author_url + "'>" + videoProperties.author_name + "</a> on <a href='http://vimeo.com'>Vimeo</a>.</p><p>" + videoProperties.description + "</p>"
});
//get second video (insert into another div)
$.getJSON('http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/' + videoList[1].id + '&byline=false&portrait=false&callback=?', {format: "json"},
function(videoProperties) {
document.getElementById("vimeoRecent2").innerHTML=videoProperties.html
document.getElementById("vimeoDescription2").innerHTML="<p><a href='" + videoList[1].url + "'>" + videoProperties.title + "</a> from <a href='" + videoProperties.author_url + "'>" + videoProperties.author_name + "</a> on <a href='http://vimeo.com'>Vimeo</a>.</p><p>" + videoProperties.description + "</p>"
});
});
});

Issues with Jquery ".append" in IE8

well, i've been having problems trying to use the ".append" in IE8, my code works fine in all browsers (even IE9), but I'm having issues with IE8.. Here's my code:
divLine = null
for(var i = ini; i < fim; i++ ){
if(i % 5 === 0){
var divLine = $("<div class='line' style='float:left;display:block;padding-top:25px;'></div>")
$("#products").append(divLine)
}
if (linkI[i] != "semLink") {
if (i != (4 + ini) && i != (9 + ini) && i != (14 + ini) && i != (19 + ini)) {
divLine.append("<div id='" + albuns[i] + "'style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" + "</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"<a class='icons-itunesSmall lfloat mtm' href='" + linkI[i] + "' target='_blank'>Itunes</a>" +
"</div>" +
"</div>" +
"<img src='http://assets.jumpseller.com/store/biscoitofino/themes/8055/space.png' width='30' style='float:left;display:block;'/>" +
"</div>")
} else {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"<a class='icons-itunesSmall lfloat mtm' href='" + linkI[i] + "' target='_blank'>Itunes</a>" +
"</div>")
}
} else {
if (i != (4 + ini) && i != (9 + ini) && i != (14 + ini) && i != (19 + ini)) {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"</div>" +
"</div>" +
"<img src='http://assets.jumpseller.com/store/biscoitofino/themes/8055/space.png' width='30' style='float:left;display:block;'/>" +
"</div>")
} else {
divLine.append("<div id='" + albuns[i] + "' style='float:left;display:block;'>" +
"<a href='" + url[i] + "'>" +
"<img src='" + imagesUrl[i] + "' width='170' />" +
"</a>" +
"<div style='width:170px;'>" +
"<h3 class='shout bare mts'>" +
"<b>" + names[i] + "</b>" +
"</h3>" +
"<h6 class='mbs'>" +
albuns[i] +
"</h6>" +
"<a class='icons-comprar lfloat mtxs mrs' href='" + linkS[i] + "' target='_blank' >Comprar </br></a>" +
"</div>" +
"</div>" +
"</div>")
}
}
}
in which:
albuns = new Array();
imagesUrl = new Array();
url = new Array();
names = new Array();
linkS = new Array();
linkI = new Array();
are already sorted arrays generated by a server.
I also took printscreens of the output in both chrome and IE8:
IE8 below:
Chrome below:
As we can notice the output in IE is completely distorted...
here's the site in question:
http://biscoitofino.jumpseller.com/catalogo
Any suggestions???
Thank you in advance!

Categories