Javascript: Namespace wrap up for normal function - javascript

I have created functions as normal way, am just trying this in namespace way. the below that i have now, for the same i just want to know how this would be in Namespace way. Any idea?
Aim: I want this piece of code in Namespace wrap up with optimization of this code.
<div class="Content" id="ThiPage">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
<div class="Content" id="ThiPage1">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
<div class="Content" id="ThiPage2">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
My current JS code is
var sampPag = document.getElementById("ThiPage");
var sampPag1 = document.getElementById("ThiPage1");
var sampPag2 = document.getElementById("ThiPag2");
function samplefunct(thisArray){
sampPag.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[1].heading;
sampPag1.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[2].heading;
sampPag2.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[0].heading;
//Body content
for(var i = 0; i < 20; i++){
sampPag.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[1].text;
sampPag.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[1].text;
if (i == 1) {sampPag.getElementsByTagName("div")[3].getElementsByTagName("img")[0].src += thisArray[1].image;}
sampPag1.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[2].text;
sampPag1.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[2].text;
if (i == 1) {sampPag1.getElementsByTagName("div")[2].getElementsByTagName("img")[0].src += thisArray[2].image;}
sampPag2.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[0].text;
sampPag2.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[0].text;
if (i == 1) {sampPag2.getElementsByTagName("div")[2].getElementsByTagName("img")[0].src += thisArray[0].image;}
}
}

You can easily move the fn into the new namespace. And add the js code in a separate external .js file.
var myns = {};
myns.globvar = {}; //global variables restricted to the namespace.
myns.funcs = {}; //Add your functions to the funcs.
myns.funcs.samplefunctest= function () {
/ * Code here */
}
Ref - http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailnamespacing

This could be as simple as an IIFE:
(function () {
var sampPag = document.getElementById('ThiPage');
var sampPag1 = document.getElementById('ThiPage1');
var sampPag2 = document.getElementById('ThiPag2');
function samplefunct(thisArray) {
sampPag.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[1].heading;
sampPag1.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[2].heading;
sampPag2.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[0].heading;
//Body content
for (var i = 0; i < 20; i++) {
sampPag.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[1].text;
sampPag.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[1].text;
if (i == 1) {
sampPag.getElementsByTagName('div') [3].getElementsByTagName('img') [0].src += thisArray[1].image;
}
sampPag1.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[2].text;
sampPag1.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[2].text;
if (i == 1) {
sampPag1.getElementsByTagName('div') [2].getElementsByTagName('img') [0].src += thisArray[2].image;
}
sampPag2.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[0].text;
sampPag2.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[0].text;
if (i == 1) {
sampPag2.getElementsByTagName('div') [2].getElementsByTagName('img') [0].src += thisArray[0].image;
}
}
}
}());
This avoids creating any globals at all. One reference I use whenever considering module patterns is this page: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html. It has reasonable coverage of different JavaScript module patterns that exist.

Related

Function not changing value of variable

I am working on an HTML page where I want function typewriter to be executed first and then for a loop to start that prints '.', to make it look like a loading screen.
This is the code I am using:
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
y = 1;
}
while (y == 1) {
var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
}
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br> Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>
The function typewriter() is getting executed but the code following it doesn't start, I assume this is because the value of y is not being set as 1. Could someone help me out here?
Thanks
Perhaps you could create another function that is called where y is being set:
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
typeEllipses();
}
}
function typeEllipses() {
var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
}
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br> Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>
You can see what is happening if you change
while(statement) {
//code
}
to
do{
//code
}while(statement)
The do...while loop only executes once. That's because it's being run one time on execution, at the time that y == 0. The while loop the way you have it never fires at all because the one time its statement is interpreted, y == 0.
If you want to call it every time typeWriter() is called, you already have a recursive loop for that function, so just put the while code in its own function and call it from inside there.
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
console.log(y)
y = 1;
}
do{
console.log("test")
/*var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);*/
}while (y == 1)
window.onload = typeWriter;
<div id="typing"></div>
Hey try this No Need For Loop
If you use while loop of infinite it will crash.
so just use setInterval and clear the interval once theed for the loading is done clear the interval using clearInterval()
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
y = 1;
}
var span = document.getElementById('myspan');
var interval = setInterval(function () {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br>
Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>
Try this instead,
var i = 0;
var txt = "//Welcome To My Playground!";
var speed = 100;
var loading;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
var span = document.getElementById("myspan");
var loading = setInterval(function () {
span.innerHTML = span.innerHTML.length == 11 ? "" : span.innerHTML;
span.innerHTML += ".";
}, speed);
// clearInterval(loading); // to stop loading dots
}
}

Pascal Triangle array not showing in HTML? How do i solve it?

<head>
<title> Pascal’s Triangle </title>
</head>
<body>
<header>
<div id="strong"> Pascal’s Triangle </div>
</header>
<div class="container">
<div>
<span id="enter"> Please enter any number: </span><input id="number" /> <br id="screen"/>
<button id="button" onclick="createPascalTriangle()"> Check »</button>
</div> <br/>
</div>
<div id="show"> </div>
<footer>
<div> ©Technical Challenge </div>
<footer>
<script>
function createPascalTriangle () {
var pascalTriangle = [];
var numRows = document.getElementById("number").value;
for (var i = 0; i < numRows; i++) {
pascalTriangle[i] = new Array(i+1);
for (var j = 0; j < i+1; j++) {
if (j === 0 || j === i) {
pascalTriangle[i][j] = 1;
} else {
pascalTriangle[i][j] = pascalTriangle[i-1][j-1] + pascalTriangle[i-1][j];
}
}
}
return pascalTriangle;
pascal = JSON.Stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
}
</script>
</body>
Pascal Triangle array not displaying in expected 'div'
How do i display these array of Pascal Triangle in HTML?
Here is my code. The 'div 'is not displaying anything
i tried the innerHTML property. the pascalTriangle output is an Array. But i'm unable to display the output in html
The problem might be:
its JSON.stringify (capitalization)
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You are doing actions after your function returns a value. The function stops being executed as soon as the return statement is reached. You should write at the end of the function:
pascal = JSON.stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
return pascalTriangle;

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

Loop through div children and bold specific text not working

I have a suggestion dropdown under an input field and I am trying to make the text in the suggestion divs bold for the portion that matches what is currently in the input field.
e.g
input: AB
dropdown: ABCDE
My current code doesn't seem to be replacing the div content with the span
JS:
BoldMatchedText(inputToMatch:string){
var outerDiv = document.getElementById("dropdown");
if(outerDiv != null){
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++){
subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
html:
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">{{reg1}}</div>
<div class="reg-list-item">{{reg2}}</div>
<div class="reg-list-item">{{reg3}}</div>
<div class="reg-list-item">{{reg4}}</div>
</div>
</form>
You need to assign the result of calling the function replace.
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
function BoldMatchedText(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
BoldMatchedText('Go');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>
Try this working sample with a benchmark. Compared with the previous answer.
function BoldMatchedText1(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if (outerDiv != null) {
var subDiv = outerDiv.getElementsByTagName("div");
for (var i = 0; i < subDiv.length; i++) {
subDiv[i].innerHTML = subDiv[i].innerHTML.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
function BoldMatchedText2(inputToMatch) {
var outerDiv = document.getElementById("dropdown");
if(outerDiv !== null) {
// Use `getElementsByClassName` instead using `getElementsByTagName('div')` JS will traverse your entire HTML file and look for all div tags, may take a little longer if you have a lot
var items = outerDiv.getElementsByClassName("reg-list-item");
// Getting the iteration length before the loop will give you performance benefit since items.length will not be checked per iteration
var len = items.length;
// Using while loop evaluating only if len is any positive number (true) except 0 (false) with reverse iteration making it faster
while(len--) {
var item = items[len].innerHTML;
// ONLY replace the text that contains the `inputToMatch`
if(item.indexOf(inputToMatch) !== -1) {
items[len].innerHTML = item.replace(inputToMatch, "<span id=\"strong\">" + inputToMatch + "</span>");
}
}
}
}
console.time('filter1');
BoldMatchedText1('Gom');
console.timeEnd('filter1');
console.time('filter2');
BoldMatchedText2('Gom');
console.timeEnd('filter2');
#strong {
font-weight: 700
}
<form>
<input type="text" id="dropdown-input">
<div id="dropdown">
<div class="reg-list-item">Ele</div>
<div class="reg-list-item">Gomez</div>
<div class="reg-list-item">Rod</div>
<div class="reg-list-item">Enr</div>
</div>
</form>

Can't get child div IDs within each parent div/class

When I try to get child div IDs within each parent div/class I get the error "Uncaught TypeError: Cannot set property '0' of undefined". I am using this javascript with scriptaculous so I have turned off the "$" shortcut.
Example HTML:
<div id="group1" class="section">
<h3 class="handle"><input type="hidden" name="groupName1" value="MyGroup1">MyGroup1</h3>
<div id="item_73548" class="lineitem">item a</div>
<div id="item_73386" class="lineitem">item b</div>
<div id="item_73163" class="lineitem">item c</div>
</div>
<div id="group2" class="section">
<h3 class="handle"><input type="hidden" name="groupName2" value="MyGroup2">MyGroup2</h3>
<div id="item_73548" class="lineitem">item d</div>
<div id="item_73386" class="lineitem">item e</div>
<div id="item_73163" class="lineitem">item f</div>
</div>
The Javascript:
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);
The output should be:
groups[0][0]="item_73548";
groups[0][1]="item_73386";
groups[0][2]="item_73163";
groups[1][0]="item_73548";
groups[1][1]="item_73386";
groups[1][2]="item_73163";
Fiddle here: http://jsfiddle.net/qy9dB/3/
You just need to make sure that groups[i] is setup as an array before you try and add 2nd level elements to the array.
$.noConflict();
var sections = document.getElementsByClassName('section');
var groups = new Array();
for (i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionID = section.id;
groups[i] = [];
var j = 0;
jQuery.each(jQuery("#" + sectionID + " .lineitem"), function () {
groups[i][j] = jQuery(this).attr('id');
j++;
});
}
console.log(groups);

Categories

Resources