show / hide div can do without jquery? - javascript

I have a script that is now working, but there's still conflict with other scripts on page that I have no control over... (hosted e-com site with limited access) - is there a way to accomplish this, but with plain javascript?
var $b = jQuery.noConflict(true);
var d = new Date();
var dayOfWeek = d.getUTCDay();
var hour = d.getUTCHours();
var mins = d.getMinutes();
var status = 'open';
if (dayOfWeek !== 6 && dayOfWeek !== 0 && hour >= 12 && hour < 22)
status = 'open';
else
status = 'closed';
if (status=='open')
$b('.orderby').show();
else
$b('.orderby').hide();

You only have 1 tiny bit of jquery in your code
if (status=='open') {
$b('.orderby').show();
}else{
$b('.orderby').hide();
}
This can be converted to
if (status=='open') {
document.querySelector('.orderby').style.visibility = "visible";
}else{
document.querySelector('.orderby').style.visibility = "hidden";
}

You can use this:
var elem = document.querySelector(".elementClass");
elem.style.display = (status === 'open') ? 'block' : 'none';

Yes. You can use querySelectorAll to get elements and loop over them and add a class that will set display: none.
show
var el = document.querySelectorAll(".orderby");
for(var k in el){
el[k].className = el[k].className.replace("hide", "");
}
hide
var el = document.querySelectorAll(".orderby");
for(var k in el){
el[k].className += 'hide';
}

you could use this:
if (status=='open') {
document.getElementsByClassName('orderby')[0].style.display = "block";
}else{
document.getElementsByClassName('orderby')[0].style.display = "none";
}

Related

error Unable to get property 'display' of undefined or null reference

<script language="javascript">
function dropOrderDropDown() {
var currentInThisElement = document.activeElement.id
var currentInThisElementArray = currentInThisElement.split('_')
var foundOneToDrop = false;
var haveOneCurrentSelected = false;
var dropDownTempArray = new Array();
if ((dropDownDivValuesString != "") || (dropDownDivValuesString != null)){
dropDownTempArray = dropDownDivValuesString.split(',');
for (i=0; i < dropDownTempArray.length - 1; i++){
if (acdf != dropDownTempArray[i]){
if (document.all[dropDownTempArray[i] + "_hideThisControl"] != null){
if (document.all[dropDownTempArray[i] + "_hideThisControl"].style.display != "none"){
if (document.all[dropDownTempArray[i] + "_dropdown"] != null){
if (document.all[dropDownTempArray[i] + "_dropdown"].style.display == "block"){
document.all[dropDownTempArray[i] + '_txtValue'].click();
}
}
}
}
}
}
}
acdf = "";
return true;
</script>
First, I would recommend using getElementById() over document.all. document.all has limited browser support. Then, bear in mind that style only gets inline style properties. So if you aren't declaring style inline, you won't get any results.
Let me know if your issues persist!

what is wrong with .this. javascript if else code?

it works if i use the first half only but i need to widen the parameters
//document.querySelectorAll('font[color="black"]');
var fonts = document.querySelectorAll('font[color="black"]');
var searchString = 'Mir';
var searchString2 = 'MirrorCreator';
for (var i = 0; i < fonts.length; i++) {
var font = fonts[i];
if (fonts[i].innerHTML.indexOf(searchString) !== - 1) {
//alert('Match');
var eventLink = 'ComeHere';
var elA = document.createElement('a');
elA.setAttribute('id', eventLink);
elA.setAttribute('name', eventLink);
font.appendChild(elA);
window.location.hash = 'ComeHere';
break;
}
else (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
//alert('Match');
var eventLink2 = 'ComeHere2';
var elA2 = document.createElement('a');
elA2.setAttribute('id', eventLink2);
elA2.setAttribute('name', eventLink2);
font.appendChild(elA2);
window.location.hash = 'ComeHere2';
break;
}
}
Here you have wrong syntax:
else (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
It should be simple
else {
or
else if (fonts[i].innerHTML.indexOf(searchString2) !== - 1) {
You need to change your if else statement.
if(// conditional)
{
// do something.
}
else if(// conditional){
// do something....
}
Your else needs to be else if, because else isn't expecting (fonts[i].innerHTML.indexOf(searchString2) !== - 1)

Javascript Expandable Header not working correctly

I am using a piece of Javascript that enables the user to expand a h3 tag in my HTML document. It is working perfectly however when I refresh my page the first time the header is contracted and then when I refresh it a second time the header is expanded again.
I would like it to just stay expanded and not contract ever but I am unsure what changes I may need to make to the code:
I should point out that when the user visits the page for the first time the header is already expanded. I do that by calling the function from within the body tag.
<body onLoad="expandcontent('sc1')">
This is the code:
var enablepersist = "on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious = "yes" //Collapse previously open content when opening present? (yes/no)
if (document.getElementById) {
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(classname) {
ccollect = new Array()
var inc = 0
var alltags = document.all ? document.all : document.getElementsByTagName("*")
for (i = 0; i < alltags.length; i++) {
if (alltags[i].className == classname)
ccollect[inc++] = alltags[i]
}
}
function contractcontent(omit) {
var inc = 0
while (ccollect[inc]) {
if (ccollect[inc].id != omit)
ccollect[inc].style.display = "none"
inc++
}
}
function expandcontent(cid) {
if (typeof ccollect != "undefined") {
if (collapseprevious == "yes")
contractcontent(cid)
document.getElementById(cid).style.display = (document.getElementById(cid).style.display != "block") ? "block" : "none"
}
}
function revivecontent() {
contractcontent("omitnothing")
selectedItem = getselectedItem()
selectedComponents = selectedItem.split("|")
for (i = 0; i < selectedComponents.length - 1; i++)
document.getElementById(selectedComponents[i]).style.display = "block"
}
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue = unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem() {
if (get_cookie(window.location.pathname) != "") {
selectedItem = get_cookie(window.location.pathname)
return selectedItem
} else
return ""
}
function saveswitchstate() {
var inc = 0,
selectedItem = ""
while (ccollect[inc]) {
if (ccollect[inc].style.display == "block")
selectedItem += ccollect[inc].id + "|"
inc++
}
document.cookie = window.location.pathname + "=" + selectedItem
}
function do_onload() {
uniqueidn = window.location.pathname + "firsttimeload"
getElementbyClass("switchcontent")
if (enablepersist == "on" && typeof ccollect != "undefined") {
document.cookie = (get_cookie(uniqueidn) == "") ? uniqueidn + "=1" : uniqueidn + "=0"
firsttimeload = (get_cookie(uniqueidn) == 1) ? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload = do_onload
if (enablepersist == "on" && document.getElementById)
window.onunload = saveswitchstate

Decrements time in javascript

(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
if (second.innerHTML != "0") {
second.innerHTML = (second.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
.....................................................................................................................................................................
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
var num = document.getElementById('num'); // the number is 20.
if (second.innerHTML != "0") {
second.innerHTML = (num.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
when I create it by for loop it not happens :
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second');
for (i=20; i<=0; i--) {
if (second.innerHTML != "0") {
second.innerHTML = i;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
}
html code:
<div id="hidden">started</div>
<p id="second">20</p>
<div onClick="doDcrements();">Download</div>
Please look at your for loop:
for (i=20; i<=0; i--)
i=20 and i<=0. It will never run.
(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
Without seeing your code, the only guess is that num.innerHTML is not giving you a string that is convertible to number. Examples:
'20' - 1 = 20
'<input name="xyz" val="20"/>' - 1 = NaN
Your HTML does't have any element with id="num". If this is the case, num will be null.
Changes
setTimeout(doDecrements,1000);
for (i=20; i >=0; i--)

Javascript - Repeated if-statements don't work

My code works (doesn't fail), but it doesn't do the right thing.
I call the "generate" function every time i want to generate a new "chunk", passing a new number into the function each time its called. It generates the chunk fine, but it doesn't generate what I want it to generate.
I want it to generate either a space, a jump, a slide, or a gap, if the previous generation was a space. But if the previous generation wasn't a space, generate a space.
It doesn't do that. It sometimes generates 2 gaps, 2 jumps, or 2 slides after each other and i have no idea why... ???
Here is my code:
var ptg = 'space'; // what was previously generated to top
var wtgt; // what is currently being generated to top
var chunktogenerateto = 0;
function generate(a){
chunktogenerateto = a;
var rand1 = Math.floor(Math.random()*100) + 1;
if(ptg == 'space' && rand1 <= 25){
wtgt = 'space';
}
else if(ptg == 'space' && rand1 <= 50 && rand1 > 25){
wtgt = 'jump';
}
else if(ptg == 'space' && rand1 <= 75 && rand1 > 50){
wtgt = 'slide';
}
else if(ptg == 'space' && rand1 > 75){
wtgt = 'gap';
}
else{
wtgt = 'space';
}
ptg = wtgt;
topGen(wtgt);
}
function topGen(g){
document.getElementById('t' + chunktogenerateto).setAttribute('src','images/terrain/t' + g + '.png');
}
I hope it's not a typo... HELP!
Where the calls to "generate" are coming from:
var chunkpos = new Array();
chunkpos[0] = -100;
chunkpos[1] = 0;
chunkpos[2] = 100;
chunkpos[3] = 200;
chunkpos[4] = 300;
chunkpos[5] = 400;
chunkpos[6] = 500;
chunkpos[7] = 600;
chunkpos[8] = 700;
chunkpos[9] = 800;
chunkpos[10] = 900;
chunkpos[11] = 1000;
var temppos = new Array();
var time1;
var millis1;
var time2;
var millis2;
var millis3;
var firstreset = true;
var pos;
var poschange;
function moveLevel(){
if(firstreset == true){
resetTime();
}
var time2 = new Date();
var millis2 = time2.getTime();
var millis3 = millis2 - millis1;
poschange = Math.floor(millis3 / 5);
for(i = 0; i < chunkpos.length; i++){
temppos[i] = chunkpos[i] - poschange;
if(temppos[i] <= -150){
generate(i);
temppos[i] += 1200;
}
pos = temppos[i];
document.getElementById('chunk' + i).setAttribute('style','left: ' + pos + 'px;');
}
}
function resetTime(){
time1 = new Date();
millis1 = time1.getTime();
if(firstreset != true){
for(i = 0; i < chunkpos.length; i++){
chunkpos[i] = temppos[i];
}
}
firstreset = false;
setTimeout('resetTime()',1000);
}
Where the calls to "moveLevel" are coming from:
window.onload = function(){
if(test = 'runnable')
{
gameLoop();
}
else
{
document.getElementById('gm').innerHTML = (gm + 'Failed to run game.');
}
}
function gameLoop(){
if(currentscreen == 'playing'){
moveLevel();
}
setTimeout('gameLoop()',0);
}
Here is a download link to a zip file containing all of the code:
ParkourFreak.zip
The code i'm having trouble with is under scripts/generation.js.
The main game page (where the generation is visible is index.html.
Rather than each if statement starting with "if(ptg == 'space' ... etc" - do this first in one simple "if not space return space".
After that you can start on your random - that should work for you.
Roughly a quarter of the time you previously had a space, it will create another, because of this code:
if(ptg == 'space' && rand1 <= 25){
wtgt = 'space';
}
Note that it's creating a space when a space was previously created.
Side note:
There's no need for the && rand1 > 25 on this line:
else if(ptg == 'space' && rand1 <= 50 && rand1 > 25){
Since you previously had if(ptg == 'space' && rand1 <= 25){, it's impossible as of that line for rand1 to be <= 25 when ptg == 'space'.
(And similarly the && rand2 > 50 on the following condition.)
Are you sure you're incrementing chunktogenerateto?
It appears to stay at 0 with the current code, is that in a segment you haven't shown?
Edit: oh, it's the argument of the function. Try logging that variable, maybe that's the problem?
// elsewhere
var wtgts = ['space','jump','slide','gap'];
// in the function
if(ptg !== 'space') {
wtgt = 'space';
} else {
var randidx = Math.floor(Math.random()*4);
wtgt = wtgts[randidx];
}
Or even in the function:
var newidx = (ptg == 'space') ? Math.floor(Math.random()*4) : 0;
wtgt = wtgts[newidx];
The weights were equal, so just pick a random index from 0 to 3 and use that to pick an action from an array.
Separate the logic for ptg being space so that you only test for it once
Consider denoting the actions as numbers instead of strings, as the assignment, comparison etc will be faster and more robust.
I thought the problem lied with the generation, when in fact all I had to do to solve it was to change this:
if(temppos[i] <= -100){
generate(i);
temppos[i] += 1200;
}
to this:
if(temppos[i] <= -100){
generate(i);
chunkpos[i] += 1200;
temppos[i] += 1200;
}

Categories