I feel new to javascript asking this and am absolutely stumped here. No idea why and trying to figure out for many many hours, but if, for example, I have this line in my script:
var listen = document.getElementsByClassName('test_this')[0];
On my local machine, when I type 'listen' into the console, it returns undefined, but if I manually type this into the console then it works. For example:
the HTML:
<p class='test_this'>hi</p>
the JS:
var listen = document.getElementsByClassName('test_this')[0];
listen.addEventListener("click", function onclick(event) {
alert('hi');
});
function testZis() {
alert('test worked');
}
alert('saysHiAnyway');
Codepen URL: https://codepen.io/anon/pen/pqZNVR
If I load the codePen URL, I get the correct alert, but on my local machine in my browser, I just get this error: Cannot read property 'addEventListener' of undefined and no alert - presumably because, for some unknown reason, the var listen declaration line isn't working.
Can someone explain what on earth is going on here? I'd be really appreciative. I have a feeling it's something unbelievably simple, yet it seems so difficult to identify. Thanks for any help.
You have a couple of options here to fix this:
Place your <script> tags below all of your HTML code, right above the closing </body> tag.
The alternative would be to wrap all of your code within a window.onload event handler like so:
window.onload = function() {
//All of your code goes here
}
Related
I've got a problem with my web application. Firebug console gives me a "ReferenceError" that nearly every function is not found. I don't really know. I didn't even change stuff in some of the functions.
A snippet of my code:
<body>
...
<tr id="08">
<td>08:00</td>
<td id="mo08" onclick="go(this)"> </td>
....
</body>
Neither the onclick functions work nor the <body onload=function()> works.
I've tried to put the script into the header, but it ain't working, neither beneath the body.
function go(element) {
var ident = element.id;
windowOpener("SomePage.jsp?i="+ident);
checkDataBase();
}
There could be any error in your file of javascript before this function i.e.
if functions are written in following order like
function foo1() {} /* If it contains error then
functions below it will not be able to recognised by compiler */
function foo2() {}
function go() {}
so check for error before go() defination
I have solved my issue now. The Problem were my tries to connect to my mysql server and get some data from it. After i deleted it out, everything worked fine for me.
The Error occured in Line 1 Column 1, so i didn't have any clues, where to find my error.
I Thank you all for your Time and Effort.
I am trying to display a div on click. The function that is supposed to make the magic happen is:
$(document).ready(function showGogoasa() {
$('.gogoasa-newsletter').show();
});
Unfortunately, it does nothing. Which makes me scratch my head for hours as I have done small things like this in the past and they worked. I am trying to make this modification on the website of a client.
When I check the firebug console it says the following: ReferenceError: showGogoasa is not defined
I tried looking on Google for this kind of error but the similar cases had this kind of issue for not declaring a variable. Well, I do not have any variables.
I am trying to display a div on click.
Your code is running the function on a ready event and doesn't give the error you describe.
Presumably (it would have helped if you had provided a complete test case) you are also trying to bind the function as a click handler, but you can't do that because you have defined it using a function expression and not a function declaration (so it doesn't create a variable called showGogoasa outside of its own scope).
Define the function separately, then assign call it and bind it as a click event handler on the ready event.
$(document).ready(function ready_handler() {
function showGogoasa() { // Define it as a variable in the current scope
$('.gogoasa-newsletter').show();
}
showGogoasa(); // call it now
$("button").on("click", showGogoasa); // call it then
});
Well, I do not have any variables.
That's the problem :)
Functions are first class objects and when you say showGogoasa() that means "Get the value of showGogoasa and call it as a function".
Using jsfiddle or providing more code would have been helpful.
One issue is that you are missing the click event handler. For example when the user clicks on X then Y should happen/show. The following simple example may help you to see how it works:
http://jsfiddle.net/fionaredmond/1vbagj12/
$(document).ready(function(){
$("#showGogoasa").click(function(){
$(".gogoasa-newsletter").show();
});
});
$(document).ready(function() {
$('#idOfYourClickerElement').on('click', function(){
$('.gogoasa-newsletter').show();
});
});
I have a strange problem and I bet it is just a really stupid error somewhere, but I just can't figure out, what's wrong with my code..
I have a website that works perfectly fine on every (common) browser on every common os.
On this page i have a searchbar, which also works perfectly fine on computer. This bar also has a jquery keyup event, to start the search.
This event does not fire on ios (first problem). So I added a button as workaround. But this also doesn't work on ios.
If it would work correctly, it should call a JS-Method that only redirects the user to the search.php page while appending a GET-Variable called query. I loaded the page on pc and the error console says:
TypeError: is not a function (evaluating 'search()')
It somehow does not seem to load this method. For whatever reason. All other JS-Methods work fine. Just this one refuses to work.
The searchbar:
<input placeholder="Search" id="searchbar">
the link looks like this:
start search
The JS-Method looks like this:
var text = document.getElementById('searchbar').value;
window.location.href="./search.php?q="+text;
Any ideas?
Seems global variable search is reserved by iOS. Try to use some another name like mySearch then it works.
BTW, you may consider using namespace or scope to avoid conflict with libraries or system.
Example:
(function() {
function search() {
alert('test');
}
document.getElementById('searchbutton').onclick = search;
})();
Or if you insist to use onclick directly in the element.
start search
<script>
var MyNamespace = (function() {
function search() {
alert('test');
}
return {
search: search
};
})();
</script>
I am writing a small library for internal use in a project that I am working on, I am an amateur Javascript developer, so mind my mistakes please.
I have written a small html file as well as javascript below it goes,
<html>
<head>
<script>
var prc = {
cng : function(evt){
console.log(evt);
}
}
</script>
</head>
<body>
<input type='text' id='prc' onkeydown="prc.cng(window.event)"/>
<body>
</html>
I tried executing this in Firefox and Chrome, not in IE Still,
When I am trying in Firefox, it gives this error "TypeError: prc.cng is not a function", and when trying in chrome it gives the "Uncaught TypeError: Object #<HTMLInputElement> has no method 'cng'".
I tried searching for this in StackOverflow, but the issues they are facing is quite different from what I am facing. Almost most of the issues faced were with jQuery involved, here please note that I am not using any kind of library and writing with plain old Javascript.
Any Help would be appreciated to enhance my understanding of the issue.
Having an element with an id that is the same as an existing JS variable is blatting the content of the variable and replacing it with a reference to the element.
The quick solution is to change either the variable name or the element id.
A more robust solution would be to keep all your data in as narrow a scope as possible. If you don't desperately need it to be global, then don't make it global and it won't be over-writable from outside the script.
Since, using intrinsic event attributes, you can only refer to variables in <script> elements if they are global, this is also a good time to stop using them and move to something modern.
// Self-executing anonymous function expression used to limit scope
(function () {
// Locally scoped prc that won't clash with the element
var prc = {
cng : function(evt){
console.log(evt);
}
}
// Event handler binding
document.getElementById('prc').addEventListener('keydown', function (evt) {
prc.cng(evt)
});
}());
Note that this script doesn't delay execution until load or domReady so place it after the input so that the input exists when the attempt to find the event handler happens.
I have found the answer to my own question, thanks to #Barmar, who has been instrumental in making me understand the problem.
When i define any element in html like this
<input type='text' id='test' onkeydown='test.fn()'/>
It means that an object is created by the browser for the same. So If I have javascript written which clashes with the id, that won't be accessible anywhere in that page.
<script>
var test = {
fn : function(){
console.log('test');
}
}
</script>
So Ideally either rename the id, or rename the object.
I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!
<SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
The error I am getting is when clicking on a drop down context menu on a page, for this line:
newImage("\/_layouts\/images\/icon1.gif");
The object doesn't accept this property or method
Code: 0
I really don't see what could happen... Any tips on what may be happening here?
Have you tried loading your scripts into a JS debugger such as Aptana or Firefox plugin like Firebug?
Why are you escaping the forward slashes. That's not necessary. The two lines should be:
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
It is hard to answer your question with the limited information provided:
You are not showing the complete script
You never said what the exact error message is, or even what browser is giving the error.
Which line number is the error supposedly coming from?
I'd recommend using Firebug in firefox for debugging javascript if you aren't already. IE tends to give bogus line numbers.
And as others have already said, the language attribute for script tags is deprecated.
Write proper xml with the " around attributes.
<script type="text/javascript">
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
</script>
should your script block not be:
<script type="text/javascript">
?
For starters, start your script block with
<script type="text/javascript">
Not
<script language=JavaScript>
That's probably not the root of your problem, but since we can't see your script, that's about all we can offer.
You probably need to enlist the help of a Javascript debugger. I've never figured out how to make the various debuggers for IE work, so I can't help you if you're using IE.
If you're using Firefox or you CAN use Firefox, make sure you have a Tools / Javascript Debugger command. (If you don't, reinstall it and be sure to enable that option.) Next, open up the debugger, rerun the problem page, and see what comes up.
How are you calling changeImages? It looks as though you are not saving a reference to the images returned by newImage. You probably want to save the results of newImage and pass that to the changeImages routine. Then changeImages should look like this:
function changeImages(a, b) {
a.src = b.src;
}
You also may want to ensure that the images have finished loading before calling changeImages.
You've posted the routine that throws the error, without posting the error or showing us how you are calling it. If none of the answers posted fix your problem then please post some detail about how you are calling the method, which specific line the error is on, and what the error message is.
You firebug to debug.
http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US
https://addons.mozilla.org/en-US/firefox/addon/1843
JSLint is also a nice resource.
http://www.jslint.com/
Using CDATA instead of the <!-- // -->
http://www.w3schools.com/XML/xml_cdata.asp
<script type="text/javascript">
<![CDATA[
]]>
</script>