if statement not evaluating condition as expected - javascript

I am using a $.getJSON function to return JSON from an API of employee salaries. For each entry, I have a counter that goes up for each employee returned. I added a list that allows the user to choose the department the employee works in as a variable to check when the function is wrong. When the check function runs for all employees, it works as expected returning 1000 employees. However, when I add in the if statement, it does add any employees to the employee counter.
I am logging the selected department to the console and can see the department is correctly selected. I think put in a string of "Department of Police" to use in the function and it return 186 employees. If I use the variable checkedValue which shows in the console the same value I would expect the same function to return 186 employees but it does not. The value is held in the JSON object as a string so I'm not sure if the wrong data would be the problem.
What am I doing wrong?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<div id="page">
<div id="content">
<div id="button-area">
<button id="check">Check the radio button</button>
<button id="action">Do Action</button>
</div>
<div id="checks">
</div>
<div>
<ul id="list"></ul>
</div>
</div>
</div>
</body>
CSS:
body {
font-family: 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;
height: 100%;
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
#page {
width: 80%;
margin: 0 auto;
border: 1px solid black;
box-shadow: 3px 3px 5px 2px black;
}
#content {
margin: 10px;
}
#button-area {
padding-top: 50px;
width: 100%;
height: 100px;
margin: 0 auto;
text-align: center;
}
JavaScript:
var url;
var myNewObject;
var myObject;
var departmentArray;
var cleanedDepartmentArray;
var checkedValue;
var budget = 0;
var employees = 0;
function setTheList() {
$.getJSON(url, function(data) {
myObject = data;
for (var i = 0; i < myObject.length; i++) {
departmentArray.push(myObject[i].department_name);
};
$.each(departmentArray, function(i, el) {
if ($.inArray(el, cleanedDepartmentArray) === -1) {
cleanedDepartmentArray.push(el);
}
});
for (var i = 0; i < cleanedDepartmentArray.length; i++) {
$('#list').html("");
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
};
});
};
$(document).ready(function() {
console.log("Initialized with " + employees + " employees and " + budget +
" budget.");
url = 'https://data.montgomerycountymd.gov/resource/54rh-89p8.json';
myObject;
myNewObject;
departmentArray = [];
cleanedDepartmentArray = [];
//set the list
setTheList();
//get checked radio button value
function getCheckedValue() {
checkedValue = "";
checkedValue = $("input[name=department]:checked").val();
console.log(checkedValue);
};
//call geojson
function getData(checkedValue) {
getCheckedValue();
$.getJSON(url, function(data) {
myNewObject = data;
console.log("my new object: ", myNewObject)
for (i = 0; i < data.length; i++) {
if (data[i].department_name === checkedValue) {
employees++;
};
};
console.log(checkedValue);
console.log(employees)
});
};
$('#check').on('click', function() {
getCheckedValue();
});
$('#action').on('click', function() {
getData(checkedValue);
});
});

There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Seeing if I can highlight this any clearer for you:
There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Just to see if I can highlight it any better:
cleanedDepartmentArray[i] + " ' <<< this bit

Related

Problems targeting the correct div id with dynamically (javascript) created divs

I'm having troubles targeting the correct div id with dynamically (javascript) created divs.
How it should function..
Each time you press the add text button a new text input is created with an incrementing id
When you type into this box the text appears in the results div
The same will repeat each time you press the add text button.
So far all of the above functions as I would expect.
The problem..
When you add a second text then try to edit the first text the id is wrong so the first text does not update.
How can I make this function as expected so no matter how many texts you add you can edit a previous one and it updates the correct id?
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext();\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext() {
document.getElementById("showtext" + (textcount)).innerText = (textcount) + ") " + document.getElementById("textarea" + (textcount)).value;
//console log id when typing to see what id is being targeted
console.log(textcount);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>
When you was getting the id to use, you was getting the number of the index. Like length. You was getting the last number. I changed a little and it worked, see below:
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext(event);\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext(e) {
var ideditaded = e.target.getAttribute("id").replace("textarea", ""); // get the id of what you are editing and remove the textarea to get only its textcount.
document.getElementById("showtext" + (ideditaded)).innerText = (ideditaded) + ") " + document.getElementById("textarea" + (ideditaded)).value;
//console log id when typing to see what id is being targeted
//console.log(ideditaded);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>

jQuery - pre-set array values for add-to-cart

I have a basic add-to-cart that allows for adding and removing cart items using checkboxes.
I want to be able to pre-set some of the items to be in the cart by getting the item's id or data-wish attribute and adding it to the array for the items.
var wish = {
items: ["handbag", "backpack"]
};
How do I allow for items to be pre-selected so that they appear in the cart and the .my-wish-add button is :checked (for the icon's checked state animation).
// Wish Function
var wish = {
items: []
};
var update_product = function(product) {};
$(function() {
//Add to wish
var addToWish = function(product, qty) {
qty = qty || 1;
var wish = getWish();
var indexOfId = wish.items.findIndex(x => x.id == product.id);
if (indexOfId === -1) {
wish.items.push({
id: product.id,
img: product.img,
name: product.name,
location: product.location,
price: product.price
});
$parent = $("#" + product.id).closest(".items__cart");
$parent
.find(".wish-icon")
.addClass("active")
.attr("data-prefix", "fas");
} else {
wish.items[indexOfId].stock = Number(product.stock);
}
//Update popup wish
updateWish(wish);
};
//Remove from wish on id
var removeFromWish = function(id) {
var wish = getWish();
var wishIndex = wish.items.findIndex(x => x.id == id);
wish.items.splice(wishIndex, 1);
$parent = $("#" + id).closest(".items__cart");
$parent
.find(".wish-icon")
.first()
.removeClass("active")
.attr("data-prefix", "far");
//Update popup wish
updateWish(wish);
};
var getProductValues = function(element) {
var productId = $(element)
.closest(".items__cart")
.find(".item__tile")
.attr("id");
var productImg = $(element)
.closest(".items__cart")
.find(".item__img")
.attr("src");
var productName = $(element)
.closest(".items__cart")
.find(".item__title")
.html();
var productPrice = $(element)
.closest(".items__cart")
.find(".cost")
.html();
var productLocation = $(element)
.closest(".items__cart")
.find(".item__location")
.html();
var productTax = $(element)
.closest(".items__cart")
.find(".circle")
.html();
return {
id: productId,
img: productImg,
name: productName,
location: productLocation,
price: productPrice,
tax: productTax
};
};
$(".my-wish-add").on("change", function() {
var product = getProductValues(this);
if ($(this).is(":checked")) {
addToWish({
id: product.id,
img: product.img,
name: product.name,
location: product.location,
price: product.price,
tax: product.tax
});
} else {
removeFromWish(product.id);
}
});
//Update wish html to reflect changes
var updateWish = function(wish) {
$(".wishlist__items").html("");
for (var i = 0; i < wish.items.length; i++) {
$(".wishlist__items").append(
"<li class='wish__item'>" +
'<div class="wish__thumb">' +
"<img src='" +
wish.items[i].img +
"' />" +
"</div>" +
'<div class="wish__info">' +
'<div class="wish__header">' +
'<div class="wish-name">' +
wish.items[i].name +
"</div>" +
"</div>" +
' <div class="wish__value">' +
"<span>Price: </span> $ " +
wish.items[i].price +
"</div>" +
"</div>" +
'<div class="wish__remove">' +
'<label class="wish__label">' +
'<input type="checkbox" id="my-wish-remove' +
i +
'" class="my-wish-remove" aria-hidden="true">' +
"<i class='fas fa-heart'></i>" +
"</div>" +
"</div>"
);
(function() {
var currentIndex = i;
$("#my-wish-remove" + currentIndex).on("change", function() {
$(this)
.closest("li")
.hide(400);
setTimeout(function() {
wish.items[currentIndex].stock = "";
update_product(wish.items[currentIndex]);
$("#" + wish.items[currentIndex].id)
.parents()
.find($(".wish-btn > input"))
.prop("checked", false);
removeFromWish(wish.items[currentIndex].id);
}, 400);
});
})();
}
};
//Get Wish
var getWish = function() {
var myWish = wish;
return myWish;
};
});
.wish__item {
display: flex;
}
.my-wish-add {
font-family: "Font Awesome\ 5 Pro";
font-weight: 900;
color: #6394f8;
}
.wish-btn {
position: relative;
cursor: pointer;
}
.wish-btn input {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.wish-icon.active {
color: green;
}
.active i.fa.fa-wishlist__list {
color: #6394f8;
}
.my-wish-remove {
font-size: 20px;
cursor: pointer;
color: rgb(109, 109, 109);
}
.my-wish-remove:hover {
color: #464646;
}
.items__wish {
border: 1px solid;
width: 150px;
}
.wish__info {
flex: 1;
border: 2px solid;
}
.wish__thumb {
display: flex;
}
.wish__thumb img {
height: 30px;
}
.wish-main {
flex: 1;
}
img {
width: 50px;
}
.wishlist__list {
margin: 20px 0;
float: right;
background: #fff;
width: 320px;
position: absolute;
border: 2px solid;
border-radius: 3px;
padding: 20px;
right: 7.5%;
}
.wishlist__items li {
list-style: none;
}
.wishlist__list-empty img {
width: 100px;
}
<script src="https://pro.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="wishlist">
<div class="wishlist__list">
<ul class="wishlist__items">
</ul>
</div>
</div>
<div class='products'>
<div class="items__cart">
<div id='headphones' class='item__title item__tile' data-wish="headphones">Product 1</div>
<img class="item__img" src="https://www.iconasys.com/wp-content/uploads/2017/06/360-Product-Photography-White-Background-Acrylic-Riser-08.jpg">
<div>
<span>$</span>
<span class='cost'>500</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></input></label>
</div>
<div class="items__cart">
<div id='backpack' class='item__title item__tile' data-wish="backpack">Product 2</div>
<div>
<h4 class="count">200</h4>
</div>
<img class="item__img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqpSgkG4AQDQOe33jI1NiW3GW2JSB-_v36aREsVyFQH55JFOJ">
<div>
<span>$</span>
<span class='cost'>460</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></label>
</div>
<div class="items__cart">
<div id='handbag' class='item__title item__tile' data-wish="handbag">Product 3</div>
<h4 class="count">400</h4>
<img class="item__img" src="https://qph.fs.quoracdn.net/main-qimg-de7d9680c4460296e461af9720a77d64">
<div>
<span>$</span>
<span class='cost'>212</span>
</div>
<label class="wish-btn">
<input type="checkbox" name="wish-check" class='my-wish-add'><i class="wish-icon far fa-heart"></i></label>
</div>

How to save results to localStorage

I am new in HTML and jQuery, and this was my first implementation, and I am not sure it's correct, I need your help, I tried to make simple counter to begin counting per click, and to store the results in localStorage, this is all I could do
but it didn't work, may you tell me what I've done wrong?
Thanks
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save', $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
You need to init first your buttons with values from localStorage. Then you don't need to retrieve them again, you just need to manipulate the value inside the html and to set the new counter in the localStorage.
Also you need to have one counter by button in your localStorage
// Just to make this snippet work,
// because localStorage is forbiden here
// database = localStorage
database = {
store: {},
getItem: function(key) {
return this.store[key];
},
setItem: function(key, val) {
this.store[key] = val;
},
}
$(function() {
$(".counter").each((_, element) => {
const $btn = $(element);
const key = `save-${$btn.attr("data-page")}`;
$btn.html(database.getItem(key) || 0);
});
$(".container li").click(function() {
const $btn = $(this).find(".counter");
const key = `save-${$btn.attr("data-page")}`;
const counter = (+$btn.html()) + 1;
$btn.html(counter);
database.setItem(key, counter);
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to load the data from the local storage when the page loads. Right now it only loads after saving, which has no effect.
Each element is also saving to the same part of the local storage, so they will be the same every time the page loads. You need to save to an index based on the data-page.
Here you go with one more solution https://jsfiddle.net/thrh78u0/
$(function() {
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save' + btn, element);
if (localStorage.getItem('save')) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save'));
}
});
});
ul {
padding: 0;
margin: 0;
list-style: none;
}
a {
text-decoration: none;
background: blue;
color: #fff;
padding: 10px;
}
ul li {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
<li data-page="facebook">
4100
</li>
<li data-page="twitter">
4100
</li>
</ul>
Hope this will help you.
Try this simple one:
$('.container li').click(function() {
if (localStorage.count) {
localStorage.count++
} else {
localStorage.count = 1;
}
})
Updated script using different variables for different counters. It loads counters values from localStorage or sets them to 0 if not available. It also uses two separate variables to store the values.
I used your code so you can see what is different and what you missed in your solution
$(function() {
var cntfb = localStorage.getItem('save-facebook');
$('.counter[data-page="facebook"]').html(cntfb ? cntfb : 0);
var cnttw = localStorage.getItem('save-twitter');
$('.counter[data-page="twitter"]').html(cnttw ? cnttw : 0);
$('.container li').click(function() {
var btn = $(this).attr("data-page");
var element = $('.counter[data-page="' + btn + '"]').html();
element++;
$('.counter[data-page="' + btn + '"]').html(element);
localStorage.setItem('save-' + btn, $('.counter[data-page="' + btn + '"]').html());
if (localStorage.getItem('save-' + btn)) {
$('.counter[data-page="' + btn + '"]').html(localStorage.getItem('save-' + btn));
}
});
});

why my h1 title hides behind input box when slideUp executes

I have the following page, which is a wikisearch page that queries multiple wikipidia pages for the search term. The page has the title and input box somewhere around the middle; however, when I click on the botton, the title slides up, and so the input box. But the input box slides all way up covering the title. I think!... how can I prevent the inputbox from covering the title? or make the title stays at the top of page? Thanks
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
console.log(searchStr);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
console.log(response.query);
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary" onclick="#">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Insted of using $('#title').slideUp(3000) try use $('#title').animate({'margin-top': '0'}, 3000);
Then the title will remain.
Also, you might want to remove onclick="#" from <button id="search" class="btn btn-primary" onclick="#">Search</button>
Example below.
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$('#title').animate({'margin-top': '0'}, 3000);
//$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Add this to the h1 class
h1 {
z-index: 1000;
}
Now let's say you needed something to then go on top of the header, you'd give that element's class a z-index of something higher than 1,000, so maybe 1,001! If you needed something to go behind, simply make it 999 or lower. Using 1,000 gives you a lot of free range in either direction (+/-) to work with.

Using JavaScript to change text on the page every half-second

So, what I'm hoping to do is change the text inside a set of <p> tags every half-second. The set of tags in question is in this block of code in my body:
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
Right below the above code I have the JavaScript that should call a function every half-second:
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
I have the function changeMatrixText defined inside my head:
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
As you see, that's supposed to set the text to a random string of 0's and 1's. But it's not working. Any idea why?
Just in case you need to see my entire code .....
<html>
<head>
<title>Simple encrypt/decrypt</title>
<style type="text/css">
body
{
background-color: #A9F5F2;
width: 900px;
padding: 0px;
}
.outerdiv
{
margin: 5px;
border: 2px solid #FF8000;
background-color: #FFFFFF;
}
.outerdiv > p
{
margin: 5px;
word-wrap:break-word
}
.outerdiv > h1
{
margin: 5px;
}
#col1
{
width: 500x;
height: 800px;
float: left;
}
#col2
{
width: 295px;
height: 1500px;
float: right;
font-family: Courier New;
overflow: hidden;
}
#title1div
{
font-family: Arial;
width: 100%;
}
#insctdiv
{
font-family: Arial;
width: 100%;
}
#iptdiv
{
height: 400px;
width: 100%;
}
#buttonsdiv
{
text-align: center;
width: 100%;
}
#inputText
{
width: 100%;
height: 100%;
resize: none;
}
</style>
<script type="text/javascript">
function encrypt()
{
var text = document.getElementById("inputText").value;
newstring = "";
/* Make newstring a string of the bit representations of
the ASCII values of its thisCharacters in order.
*/
for (var i = 0, j = text.length; i < j; i++)
{
bits = text.charCodeAt(i).toString(2);
newstring += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress newstring by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
newstring = newstring.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
document.getElementById("inputText").value = newstring;
}
function decrypt()
{
var text = document.getElementById("inputText").value;
text = text.trim();
text.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
document.getElementById("inputText").value = text;
}
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
</script>
</head>
<body>
<div id="col1">
<div class="outerdiv" id="title1div">
<h1>Reversible text encryption algorithm</h1>
</div>
<div class="outerdiv" id="insctdiv">
<p>Type in or paste text below, then click <b>Encrypt</b> or <b>Decrypt</b></p>
</div>
<div class="outerdiv" id="iptdiv">
<textarea id="inputText" scrolling="yes"></textarea>
</div>
<div class="outerdiv" id="buttonsdiv">
<button onclick="encrypt()"><b>Encrypt</b></button>
<button onclick="decrypt()"><b>Decrypt</b></button>
</div>
</div>
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
</body>
</html>
In essence, I'm trying to make the right column of my page keep printing inside a new string of 0's and 1's every half-second, kinda like on the computer screen on the movie The Matrix, if you catch my drift.
According to MDN, the elements with a value attribute include <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>. You'll need to set the innerHTML instead.
document.getElementById("matrixText").value = newtext;
to
document.getElementById("matrixText").innerHTML = newtext;
and
setInterval("changeMatrixText()", 500);
to
setInterval(changeMatrixText, 500);
Working Demo
document.getElementById("matrixText").value = newtext;
.value is used for form fields instead use
document.getElementById("matrixText").innerHTML = newtext;
in your changeMatrixText function
Here's an example of how you can do this:
http://jsfiddle.net/35W4Z/
The main difference is that a <p> element doesn't have a .value attribute. Instead, use the innerHTML attribute (as shown in the JSFiddle example)
Hope this helps!
Well for fun, I stuck this in a fiddle: http://jsfiddle.net/jdmA5/1/
So two things, mostly:
1) You can't set the "value" of a div element. You have to set the .innerHTML:
document.getElementById("matrixText").innerHTML = newtext;
2) This could be due to the fact I built this out in fiddle, but setInterval is notorious for not running like you expect unless you give each iteration its own memory space. I did this by wrapping the call to changeMatrix in a anonymous function:
setInterval(function() {changeMatrixText();}, 500);
Check out the jsfiddle link to see it in action.
Have you tried changing the setInterval method to accept the first argument as the function itself (the name, minus the parentheses), rather than a string...
As you are not passing any parameters explicitly, you can invoke the function as follows:
setInterval(changeMatrixText, 500);
Should you have needed to supply some parameters, then the following would work:
setInterval(function() {
changeMatrixText(myParam1, myParam2); // etc, etc
}, 500);

Categories