Why is my Javascript not working? - javascript

This is my Javascript:
<script type="text/javascript">
function contactChange() {
var contact = document.getElementbyId("contact");
if (contact.style.display == "none") {
contact.style.display = "block";
} else {
contact.style.display = "none";
}
}
</script>
And here is my site:
http://www.andrewjalexander.com/

It's document.getElementById, not document.getElementbyId. (In JS, name of variables and functions are case-sensitive)
Debugging tip : Look at the JS console (F12 in Google Chrome and IE9, Ctrl+Shift+K in Firefox). In this case, following error can be seen:
It shows where the error happened (line 260 in your HTML/JS code) and what the error is(Object #<HTMLDocument> has no method getElementbyId).

It's getElementById, not getElementbyId. Note the upper case "B".

You're going to hate yourself for this, but you put getElementbyId() instead of getElementById(). Note the capitalized "B" in the second version.

Its getElementById in place of getElementbyId

Try to hide then show a element on scroll I had to go this route. Basically i tried to use window so I used 'body'
$(document).ready(function() {
$('body').scroll(function() {
var scroll = $('body').scrollTop();
if (scroll <= 50 ) {
console.log(scroll);
we
} else {
$("#label").css('fill', 'none');
$(".label").addClass(".transition");
}
if (scroll <= 150) {
$(".sizeLG").css('color', '#ffffff');
} else {
$(".sizeLG").css('color', '#00000000');
$(".sizeLG").addClass(".transition");
}
});
});

Make sure your id or class you used in html code will accordingly .(dot) Or #(hash) with their name.
Ex:
For id:
html:
<div id= idName>
****Some code****
<\div>
Javascript:
var VariableName = document.querySelector( "#idName");
Or
var VariableName = document.getElementById( "#idName");
For class:
html:
<div id= className>
****Some code****
<\div>
Javascript
var VariableName = document.querySelector( ".className");
Or
var VariableName = document.getElementById( ".className");

Related

External Javascript Not Working in Firefox

I have just hit an odd problem with an external javascript file. It works perfectly in Edge and Chrome but not in Firefox (51.0.1).
I have a number of scripts at the bottom of the body of the page, like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/adblocker.js"></script>
<script>
$(document).ready(function() {
$('.dir_hotel').keyup(function(event) {
if (event.keyCode == 13) {
this.form.submit();
return false;
}
});
});
</script>
<?php if ($mobile_browser > 0) { ?>
<script>
/* MOBILE COLLAPSE MENU */
(function($) {
$.fn.collapsable = function(options) {
// iterate and reformat each matched element
return this.each(function() {
// cache this:
var obj = $(this);
var tree = obj.next('.nav');
obj.click(function(){
if( obj.is(':visible') ){tree.toggle();}
});
});
};
})(jQuery);
$(document).ready(function(){
$('.slide-trigger').collapsable();
$(".slide-trigger").click(function(){
$('.slide-trigger').html($('.slide-trigger').text() == 'Collapse MENU' ? 'MENU' : 'Collapse MENU');
});
});
</script>
<?php }?>
</body>
The adblocker.js file doesn't run. I've tried adding an alert as the first line of the .js file and the alert never appears. I've checked the console in the browser and that shows the file is not loading.
If I replace
<script src="js/adblocker.js"></script>
with
<script>
window.onload=function(){
var clientHeight = document.getElementById('travins').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("insnote");
node.innerHTML = "<a href='https://clkuk.tradedoubler.com/click?p=18211&a=1906311&g=232597' target='_blank'>Columbus Direct Travel Insurance</a>";
}
var clientHeight = document.getElementById('flights').clientHeight;
if (clientHeight < 50) {
var node = document.getElementById("flightnote");
node.innerHTML = "<a href='http://www.kqzyfj.com/click-7782323-11015988-1440520708000' target='_blank'>Skyscanner</a>";
}
var clientHeight = document.getElementById('carhire').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("hirenote");
node.innerHTML = "<a href='http://www.zestcarrental.com/click.php?adm=1018&adt=14' target='_blank'>Zest Car Rental</a>";
}
var clientHeight = document.getElementById('parking').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("parknote");
node.innerHTML = "<a href='https://clkuk.tradedoubler.com/click?p=20642&a=1906311&g=20842820' target='_blank'>Purple Parking</a>";
}
var clientHeight = document.getElementById('brittany').clientHeight;
if (clientHeight < 20) {
var node = document.getElementById("ferrynote");
node.innerHTML = "<a href='http://being.successfultogether.co.uk/click.asp?ref=731409&site=6792&type=b3&bnb=3' target='_blank'>Brittany Ferries</a>";
}
};
</script>
it works perfectly.
I've tried js/adblocker.js, /js/adblocker.js and mydomain.com/js/adblocker.js and that makes no difference. I've also double-checked that the file is actually uploaded, which it is. I must be doing something stupid, but what?
As Joe correctly suggested, the Adblock Plus extension was blocking the adblocker.js file. Changing the file name to blocker.js has solved the problem.
I have to say that I think this is a mighty crude way of filtering advertising, as there must be so many innocent ways that a file might have "ad" in the name. I'll be watching for this in future whenever my Firefox does something unexpected.
Try to put your JavaScript code between this codes
(function($) { // your code here })(jQuery); in JavaScript file. It work with me.

Change the height of div using javascript

I want to change the height of div when I scroll
#H {
position: fixed;
height: 200px;
background: red;
width: 200px
}
<div style="height:2000px; position:relative">
<div id="H"></div>
</div>
<script type="text/javascript">
window.onscroll = function() {
myFunction()
};
function myFunction() {
VAR X = document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.css("height": "100px");
} else {
X.css("height": "200px");
}
}
</script>
But the code is not working. In the above code I tried to change the height of the div with id="H" on scroll from 200, that I have mentioned in the CSS to 100, but the JS is not running.
You have some problem in JavaScript.
Change it to like:
<script>
window.onscroll = function() {myFunction()};
function myFunction() {
var X=document.getElementById("H");
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
X.style.height = "1000px";
}
else {
X.style.height = "200px";
}
}
</script>
VAR X should be var X
And
X.css("height":"1000px"); change style like X.style.height = "1000px";
Working Fiddle
there are a few javascript errors in your code.
VAR X=document...
"var" has to be lower case, not upper case.
X.css(...)
"css" is not a function. Use X.style.height instead.
Generally look into how to debug javascript code. A good browser is your friend with this (e.g. Firefox or Chrome). Use console.log("foo"); to print a message or a variable to the browsers console to see what happens in your code. You can also use step by step debugging.
If you use the JavaScript console in your browser, you can see that document.getElementById("H").css is not a function.
Instead use for example document.getElementById("H").style.height = "300px";
CSS is not directly accessible in JavaScript unless you use getComputedStyle API, however the class can be accessed using element.className and changed as long as you have the relevant class already created.
element.style.property is how you change inline styles. There is a big difference in both, in that one is part of the DOM structure while the other is connected to the DOM via a class name and the stylesheet.
Specific to you question:
Here is the fiddle
window.onscroll = function() {myFunction()}; is simply window.onscroll = myFunction it is the same and more idiomatic.

getElementById not working within if statement - Troubleshooting

I have a simple JS script to swap out elements containing Flash and replace them with other formats for users who don't have Flash installed.
var hideclass="hidden"
var showclass="empty"
function flashFixMain(){
if (swfobject.hasFlashPlayerVersion("7.0.0")) {
document.getElementById('logoflash').className=showclass;
document.getElementById('logononflash').className=hideclass;
} else {
document.getElementById('logoflash').className=hideclass;
document.getElementById('logononflash').className=showclass;
}
}
And put simply, it doesn't work.
The if statement works fine - putting an alert in the appropriate place pops up fine.
I've checked the source of the appropriate page(s) online, and the element name pops up exactly as written (and only once!).
The class names work fine, as they are used as defaults on the page at the start.
So does anyone have any ideas what I might have missed?
change
document.getElementById('logoflash').class=showclass;
to
document.getElementById('logoflash').className = showclass;
it's className, not class
Instead of using .class you need to use the .className property; for instance:
document.getElementById('logoflash').className = showclass;
In modern browsers you can also use .classList to add a class rather than replace all existing classes:
document.getElementById('logoflash').classList.add(showclass);
As an aside, you could consider moving a few statements around like this:
var hasFlash = swfobject.hasFlashPlayerVersion("7.0.0"),
logoFlash = document.getElementById('logoflash'),
logoNonFlash = document.getElementById('logononflash');
logoFlash.className = hasFlash ? showclass : hideclass;
logoNonFlash.className = hasFlash ? hideclass : showclass;
I wrote up a quick test scenario and without seeing more of your environment, do not see anything that should keep this from working as expected.
The one thing I did notice while doing a write up w/o using jQuery (which I guess you are NOT using?) is that your 'addClass' is really a 'REPLACE' class value. You are simply setting it to a single class.
This makes me think, not having seen your environment, that some OTHER classes might be already assigned to your elements that are getting wiped out. This could be causing unexpected behaviour if some of your display is dependent on these other classes...
Without seeing more of your scenario, that is the only thing that seems like it might be an issue.
Anyway, here is my test setup. You might find something in this useful.
<div id="logoflash" class='something'>
Logoflash
</div>
<div id="logononflash" class='else' >
logononflash
</div>
<script>
var swfobject = {FlashPlayerVersion: '7.0.1', hasFlashPlayerVersion: function(v) {if(v == this.FlashPlayerVersion) return true; else return false;}, myName: 'fakeSWObject' };
console.log(swfobject)
var hideclass = "hidden"
var showclass = "empty"
var getById = function(sID) { return document.getElementById(sID); };
var addClass = function(sID, sClass) { getById(sID).className += ' ' + sClass };
function toggleEl(sID, bState){
console.log('begin toggleEl')
console.log('bState: ' + bState)
try {
if(bState == undefined) {
console.log('Toggling by element state');
getById(sID).style.display = getById(sID).style.display == 'none' ? 'block' : 'none';
} else {
console.log('Toggling by argument');
getById(sID).style.display = !!bState ? 'block' : 'none';
}
} catch (err) {
console.log(err);
}
}
function flashFixMain(){
if (swfobject.hasFlashPlayerVersion("7.0.0")) {
console.log('Is Flash 7.0.0');
toggleEl('logoflash', true);
toggleEl('logononflash', false);
addClass('logoflash', hideclass);
addClass('logononflash', showclass);
} else {
console.log('Is NOT Flash 7.0.0');
toggleEl('logoflash', true)
toggleEl('logononflash', false)
addClass('logoflash', showclass);
addClass('logononflash', hideclass);
}
}
$(function(){ // Yes, this is jQuery to fire after doc is ready
flashFixMain();
})
</script>
use Jquery:
$("#logoflash").addClass(hideclass);
or
$('#logoflash').toggleClass(hideclass, swfobject.hasFlashPlayerVersion("7.0.0"));

Unable to parse onClick text using DOM

All that I have read says to use the element.onclick property, but that doesn't seem to be working in my situation. I'm trying to parse the number: 629216818 and set it to a varialbe: fbid. This is a Greasemonkey script, so the HTML can't be edited directly. I'm no pro, so I may be just doing something stupid, but here is my HTML and Javascript:
<div id="petRightContainer">
<a title = "Pet trainer bonus: Your companion will level 5% faster." href="setup.php?type=companion&gtRandom=8167343321487308">
<div class="petRight" style="background-image:url(/fb/res/gui4/companion/cu_sith.jpg)"></div>
</a>
<div class="petRightLevel">
Dog
</div>
etc.
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
if ( document.getElementsByClassName("petRightLevel")[0]){
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
codeStore = element.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
The problem is in this line:
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
If you are using Firefox and other browsers which support document.getElementsByClassName and in your HTML, there are spaces between <div class="petRightLevel"> and
<a href="#" onClick= ...>
, the firstChild is actually a text node not the link. All you need to do is remove the spaces and/or line break in between the two elements.
If you are using IE, the problem is still at the same line of the javascript because IE doesn't support document.getElementsByClassName up until version 8.
Update: The following javascript code work for all the browsers I tested without touching HTML:
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
var divs = document.getElementsByTagName("div");
var link = null;
for (var i=0;i<divs.length;i++)
{
if(divs[i].getAttribute("class") ==="petRightLevel")
{
link = divs[i].getElementsByTagName("a")[0];
break;
}
}
if (link){
codeStore = link.onclick;
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
}
document.write(fbid);
</script>
If you only need to get the anchors, it would be much simpler than this.
I think this might work for you.
<script type="text/javascript">
fbid = 0;
fbidRegex = /\d{3,}(?=&fromWall=1)/;
if(document.getElementsByClassName("petRightLevel")[0]){
element = document.getElementsByClassName("petRightLevel")[0].firstChild;
// callback function to execute when the element onclick event occurs.
codeStore = element.onclick = function(){
fbid = fbidRegex.exec(codeStore);
document.write("it is working ");
document.write(fbid);
}
}
</script>

jQuery difficulties in FireFox & XHTML

I have recently made the switch from HTML to XHTML... don't get me started on the "why" - let's just say it wasn't an option. Anyhoo...
This function worked fine in IE and FF when I was HTML, but now with XHTML I get the following error in FF:
heightElement is undefined
now here is the statement where I define heightElement
function revBars(isEFBOutput, isIXPPreview) {
if (!isIXPPreview) isIXPPreview = false;
var heightElement =
$('<div id="resizeDetectingElement" style="position:absolute; left:-9999999px height:1em;"> </div>')
.prependTo('body')
.get(0);
heightElement.currentHeight = heightElement.offsetHeight; // FireBug says the error is here.
insert();
window.onresize = refresh;
setInterval(
function() {
if (heightElement.currentHeight != heightElement.offsetHeight) {
heightElement.currentHeight = heightElement.offsetHeight; refresh();
}
}, 500);
function insert() {
var px = "px";
var color = (document.styleSheets[0].href.match("ftidStyleDay")) ? "black" : "white";
$revMarks = $('.RevMark').removeClass('RevMark').addClass('UnMarked');
if (!$revMarks.length) $revMarks = $('.UnMarked');
$revMarks.each(function() {
$('<div class="RevBar" />').css({
'background-color': color,
'width': '2px', 'position': 'absolute',
'left': (isEFBOutput && !isIXPPreview ? '.25em' : '-.75em'),
'height': this.offsetHeight,
'top': offset(this) + px
}).prependTo('body');
});
}
function refresh() { $('.RevBar').remove(); insert(); }
function offset(obj) {
var top = 0;
if (obj.offsetParent) {
do {
top += obj.offsetTop;
} while (obj = obj.offsetParent);
}
if (document.all && (!isEFBOutput || (isEFBOutput && isIXPPreview))) top -= 15;
return top;
}
}
any ideas why this is throwing an error in XHTML in FF? It still works in IE.
EDIT: Again, this code worked perfectly in FF and IE until I switched to XHTML. Firefox still creates a DOM for XHTML, right?
I rewrote some of your example, as you have errors and is incomplete with function calls that are not in the example:
$(document).ready( function(){
function revBars(isEFBOutput, isIXPPreview){
var test = "<div id=\"someElement\">whatever</div>";
$('body').prepend(test).get(0);
var heightElement = $('#someElement');
console.log( heightElement);
}
revBars();
});
At this point the heigthElement exists and the div is added to DOM.
Please provide correct problems in order to get them solved.
UPDATES
//var heightElement = $('<div id="resizeDetectingElement">whatever</div>').prependTo('body').get(0);
// this statement doesn't work
var heightElement = $('body').prepend('<div id="resizeDetectingElement">whatever</div>');
// this does
console.log(heightElement);
This is basically the same as first example.
The request that you made is to add a div before the element body and then get the first element of the body. The prependTo already returns the matched items so the get was irelevant. And you are attaching an element before the body so is normal that your variable will be empty.
Try my code and remove the downvote as not to many people had this kind of patience with your supercode.
UPDATE 2
This is an usage example for prepend() and prependTo().
<html>
<head>
<script type="text/javascript" src="../lib/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$("#test_A").prepend('<div id=\'test_B\'>B</div>');
$("#test_C").prependTo( $('#test_A'));
var x = $('<div id="resizeDetectingElement">D</div>').prependTo('body').get(0);
console.log( x ); // returns the div
$(x).append('some text'); //works
});
</script>
</head>
<body>
<div id='test_A'>A</div>
<div id='test_C'>C</div>
</body>
</html>
I hope this will help to make your code work. USE $(heightElement) not just heightElement which is the div not the jQuery object.

Categories