Change div bgcolor onkeypress - javascript

Trying to change the background color of all my divs using a onkeypress event. R = Red , B=White, V=Green. When press R it works but when i press V or B it gives me the alert.
I tried without return, with a switch(actualy im supposed to do this with a switch). Teacher cancelled class today so I wasnt able to check it out with him .And I Wont see him til next week. I tried things and other things for 2-3 hours and im totaly stuck Please help.. Thanks in advance
window.onkeypress = function colorchange(x)
{
if (x.keyCode == 114)
{ var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "red";
}return;
}
if (x.keycode == 118)
{
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "green";
}return;
}
if (x.keycode == 98)
{
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "white";
}return;
}
else
{
alert("this key doesnt do anything")
}
}
}

The variables are case-sensitive. You have keycode and it should be keyCode. Looks like you should also be using else if().
window.onkeypress = function colorchange(x) {
if (x.keyCode == 114) {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = "red";
}
return;
} else if (x.keyCode == 118) {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = "green";
}
return;
} else if (x.keyCode == 98) {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = "white";
}
return;
} else {
alert("this key doesnt do anything")
}
}
body {
background: #eee;
}
div {
width: 100px;
height: 100px;
background: #aaa;
}
<div></div>

You are comparing x.keycode instead of x.keyCode in the second and third if statements. You should also chain the conditions using else if.
window.onkeypress = function colorchange(x)
{
if (x.keyCode === 114) {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "red";
}
return;
}
else if (x.keyCode === 118)
{
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "green";
}
return;
}
else if (x.keyCode === 98)
{
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++)
{
divs[i].style.backgroundColor = "white";
}
return;
}
else
{
alert("this key doesnt do anything")
}
}
See working jsfiddle here.

Related

How to reduce time of execution for javascript code

Below is my code which is taking time in the for loop to extract data from one object and filling another object. Is there any way to reduce the time of execution? I have tried a while loop but it is not helping that much. Kindly help
function SetGridWithData(result) {
if (!result) {
return;
}
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (result.length >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
} else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
} else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < result.length; i++) {
boxOfJson.push(result[i]);
}
}
}
I am trying to implement paging which is done, but 100 data per page first it will check page no 0 if it is then loop one and if other than 0 than else case.
You could try caching result.length at the beginning of your function (following the if check at the beginning)..
function SetGridWithData(result) {
if (!result) { return; }
var resultLength = result.length;
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (resultLength >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
}
else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
}
else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < resultLength; i++) {
boxOfJson.push(result[i]);
}
}
}

can any one tell me whats the wrong with code

function MoveAddToCartAccordingly()
{
var elems = document.getElementsByClassName('box-collateral box-related');
var av = document.getElementsByClassName('availability in-stock');
var sp = document.getElementsByClassName('product-options');
var ac = document.getElementsByClassName('add-to-cart');
var first = document.getElementsByClassName('item first');
var second = document.getElementsByClassName('item');
for(var k = 0; k < sp.length; k++){
if (getComputedStyle(sp[k]).visibility == "visible")
{
for (var i = 0; i < elems.length; i++) {
if (getComputedStyle(elems[i]).visibility == 'visible') {
for (var j = 0; j < av.length; j++) {
av[j].style.visibility = 'visible';
av[j].id = "someID";
elems[i].appendChild(av[j]);
}
}
else
{
for (var s = 0; s < av.length; s++) {
av[s].style.visibility = 'hidden';
}
for (var l = 0; l < ac.length; l++) {
ac[l].style.marginTop = "-500px";
ac[l].style.marginLeft = "-20px";
}
}
}
}
return;
}
for (var p = 0; p < elems.length; p++) {
if (getComputedStyle(elems[p]).visibility == 'visible') {
for (var q = 0; q < av.length; q++) {
av[q].style.visibility = 'visible';
av[q].id = "someID";
elems[p].appendChild(av[q]);
}
if(elems[p].style.marginTop == "-610px")
{
elems[p].style.marginTop = "-640px";
}
for(var r = 0; r < first.length; r++)
{
if(getComputedStyle(first[r]).visiblity == 'visible'){
for(var m = 0; m < ac.length; m++)
{
if(ac[m].style.marginTop == "-120px")
{
ac[m].style.marginTop ="-140px";
}
}
}
else if(getComputedStyle(first[r]).visiblity == 'visible' && getComputedStyle(second[r]).visiblity == 'visible' )
{
for(var n = 0; n < ac.length; n++)
{
if(ac[n].style.marginTop == "-120px")
{
ac[n].style.marginTop ="-140px";
}
}
}
}
}
}
}
window.onload = MoveAddToCartAccordingly;
can any one whats the wrong with code here actually i am checking if div product option is visible then again i am checking if div with class "box-colatral box-related" if visible if it is not then i am hidding other tag p with class Availability-in-stock and moving add-to- cart div to top position but that one is not working
You have a return statement in your first for loop. I imagine that you are always going to bail on the function call after the first iteration of that loop.

"Unable to get value of the property 'style'" when trying to change style in IE

Have written a function for cycling through the questions in a online quiz. I works fine in every browser but IE (god I wish IE would just curl up and die). Function is below.
function cycleQs() {
var qs = document.getElementsByName("quizQ");
var nextQBtn = document.getElementById("btnNextQ");
var i = 0;
var curQ = -1;
for (i = 0; i < qs.length; i++) {
if (qs[i].style.display == "block") {
curQ = i;
}
//qs[i].style.display = "none";
}
var valid = false;
if (curQ > -1) {
var qId = qs[curQ].id.replace("dv", "");
var inps = document.getElementsByName(qId);
if (inps.length > 0) {
if (inps[0].type == "radio") {
for (i = 0; i < inps.length; i++) {
if (inps[i].checked) {
valid = true;
}
}
} else if (inps[0].type == "hidden") {
valid = true;
for (i = 0; i < inps.length; i++) {
if (inps[i].value <= 0) {
valid = false;
}
}
}
} else {
valid = true;
}
} else {
valid = true;
}
if (valid == true) {
for (i = 0; i < qs.length; i++) {
qs[i].style.display = "none";
}
if (curQ < (qs.length - 1)) {
qs[curQ + 1].style.display = "block";
if (curQ == (qs.length - 2)) {
var scoreDv = document.getElementById("dvScore");
nextQBtn.style.display = "none";
var answers = getAnswers();
//alert(answers)
scoreDv.innerHTML = "Processing";
processResults(answers);
}
} else {
qs[0].style.display = "block"; // Problem occurs here when function first loads
}
} else {
alert("You must select an answer before you can proceed");
}
}
Any ideas of a work around for this?
document.getElementsByName is likely not returning anything, because of IEs implementation: see here
so qs[0] probably doesn't exist

Mark unmark javascript?

I've got a function to select all checkboxes in a table:
<script type="text/javascript">
function checkAll() {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = true;
}
}
}
But I can't get it to uncheck them all if they are checked. How could I do that?
<th width='2%'>Mark</th>";
Also in javascript is it possible to rename "Mark" to "Un-Mark" if I execute checkAll()?
This should do both of the things u want:
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if(elems[i].checked == true){
elems[i].checked = false;
}
else{
elems[i].checked = true;
}
}
}
if(obj.innerHTML == 'Mark') { obj.innerHTML = 'Unmark' }
else { obj.innerHTML = 'Mark' }
}
html:
<th width='2%'>Mark</th>";
1) why don't u use some js framework, like jQuery?
2) to remove checked, use elems[i].removeAttribute('checked') or set elems[i].checked = false;
3) to rename, you have to set it's innerHTML or innerText to Un-Mark
Add a little more logic to see if they're already checked. This will invert their current checked state.
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
if (!elems[i].checked) {
elems[i].checked = true;
}
else elems[i].checked = false;
}
}
If you just want to uncheck all, simply use:
elems[i].checked = false;
This will check them all regardless of their current state, or uncheck them all, depending on the current text of "Mark" or "Unmark".
<script type="text/javascript">
function checkAll(obj) {
var tab = document.getElementById("logs");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
var state = obj.innerHTML == 'Mark';
for (var i = 0; i < len; i++) {
if (elems[i].type == "checkbox") {
elems[i].checked = state;
}
}
obj.innerHTML = state ? 'Mark' : 'Unmark';
}
And then the HTML changes to:
<th width='2%'>Mark</th>";
To uncheck, try:
elems[i].checked = false;
i sugest you use jquery, everything is easier.
with jquery you just have to do something like this (+/-):
$(function(){
$('a.ClassName').click(function(){
var oTbl = $('#tableID');
$('input[type="checkbox"]', oTbl).attr("checked", "checked")
});
})

Javascript loop continue,or break to display?

Javascript loop continue,or break to display?
This is my code use for show or hide some data in table
if (type=='SHOW') {
for(var i = 0; i<list_tr.length; i++) {
document.getElementById(list_tr[i]).style.display = '';
}
else if (type=='SHOW_EXCEPT'){
document.getElementById(list_tr[0]).style.display = 'none';
document.getElementById(list_tr[1]).style.display = '';
for(var i = 2; i<list_tr.length; i++) {
document.getElementById(list_tr[i]).style.display = 'none';
}
}else{
for(var i = 0; i<list_tr.length; i++) {
document.getElementById(list_tr[i]).style.display = 'none';
}
}
In else case:
I want to hidden all but show list_tr[2] iftype=='SHOW_EXCEPT'
How can I do in this case?
thanks
if (type=='SHOW')
{
for(var i = 0; i<list_tr.length; i++)
{
document.getElementById(list_tr[i]).style.display = '';
}
}
else
{
for(var i = 0; i<list_tr.length; i++)
{
if (i==2||type=='SHOW_EXCEPT')
document.getElementById(list_tr[i]).style.display = '';
else
document.getElementById(list_tr[i]).style.display = 'none';
}
}
That should do the trick if I have understood the question correctly
Not sure I understand the question correctly, but it looks like you need else if:
if (type == 'SHOW') {
// Do something
} else if (type == 'SHOW_EXCEPT') {
// Do something else
} else {
// Do something different
}

Categories

Resources