Javascript: getValueProperty of null? - javascript

I am trying to write a single function to move an element, but I am encountering this error:
Uncaught TypeError: Cannot call method 'getPropertyValue' of null
function Mover() {
this.move = move;
// Name of the moving element, property to change, endPoint - where to end the movement
function move(element, property, endPoint) {
var element = document.getElementById(element);
// Get value of the desired property and turn it into number so that it can be incremented
var propertyValue = window.getComputedStyle(element).getPropertyValue(property);
var propertyValueInt = parseInt( propertyValue.substr(0,propertyValue.length-2) );
// This is where error starts: for some reason it says the aforementioned error
var moveit = function() {
propertyValueInt = propertyValueInt + 1;
element.style.property = propertyValueInt + "px";
};
window.setInterval(moveit, 500);
}
}
Where could the error be? I realize that it somehow rewrites the element property so that it is null, but why?
Thank you

The error comes from getComputedStyle(element).getPropertyValue(property);, since element can't be recognized as a HTML element. You've to fix the value of element to refer an existing HTMLElement. There's a typo/wrong text in the function call, or an element with the said id doesn't exist at the time this function is executed.
There's also an error in moveit(). When property is a variable name, this doesn't do what you expect:
element.style.property = ...
You need to use bracket notation:
element.style[property] = ...

Related

__V8_EXCEPTION: Uncaught SyntaxError: Illegal return statement

I am using a CEF3 based browser.
It supports adding / evaluating code without having to define a function.
I also don't have to state
"<script type = "text/javascript">
etc.
Instead, I can just pass a string to like this:
Me.webkitx1.Eval(somestring)
It works fine.
Here is a code that I use to show the focus in the first found input element when the page has loaded.
Because "element" may also be null / empty / nothing, I have tried adding "return;" in one line.
However, since I do not define a function, it doesn't allow me to use "return;", I guess...
What could I do instead?
I would like to avoid using a bigger if-then-clause.
Thank you!
var element = document.querySelector("*[autofocus]");
if (element)
{
}
else
{
element = document.querySelector("form input:not([type=hidden])");
}
if (element)
{
}
else
{
return; // not working. The error is: "__V8_EXCEPTION:Uncaught SyntaxError: Illegal return statement"
}
element.selectionStart = element.selectionEnd = element.value.length;
element.focus();
var y = element.getBoundingClientRect().top + window.scrollY;
window.scroll(
{
top: y,
behavior: "smooth"
});

Trying a closure the wrong way?

I can't figure out what's wrong with the following code and why would it work when I do it using the second way. Can anyone please help me understand this?
I have this following Javascript code:
var clsFunc = function(prefix) {
var id = 0;
return function() {
id = id + 1;
console.log(prefix + id);
}
}
First way (did not work):
If I try to call this function like this nothing happens
clsFunc('div')
Second way (worked)
var getId = {'div': clsFunc('div')}
getId.div()
Result:
div1
undefined
getId.div()
Result:
div2
The clsFunc function creates a function and returns it. So just doing
clsFunc('div');
...is pointless, because it creates a function and then just throws it away, because you didn't store it anywhere.
The second way stores the function that was created in an object property. That function has a reference to the context that created it (the call to clsFunc), even though that call has returned, which contains the id variable. When you call the function (getId.div()), it adds 1 to id and then outputs the prefix ("div") followed by the new value if id (1, then 2, then, 3, etc.).
You don't need an object for your second way, you could just use a variable:
var clsFunc = function(prefix) {
var id = 0;
return function() {
id = id + 1;
console.log(prefix + id);
}
};
var f = clsFunc('div');
f(); // "div1"
f(); // "div2"
(The undefineds you're seeing are just because you're running this in a JavaScript console that shows you the result of calling the function; since the function doesn't return anything, the result of calling it is undefined.)

Cannot set a ID attribute to a created DOM element in JavaScript

I'm trying to set a ID to a element that was created with JavaScript. However, when I run the code I just get the following error message:
Uncaught TypeError: dwarfButton.setAttribute is not a function
I did research around here and it pretty much says that if I want to add a ID attribute to one of my created elements, I have to use setAttribute("id", "whatever-else-here"), but instead I get a error message stating that it's not a function?
$(document).ready(function() {
game.start();
});
var
game = {
start: function() {
logMessage("Welcome to the Arena!");
logMessage("Select your Fighter.");
var dwarfButton = chatbox.appendChild(document.createElement("button")).textContent = "DWARF";
dwarfButton.setAttribute("id", "dwarf");
},
You're problem is on these lines:
var dwarfButton = chatbox.appendChild(document.createElement("button")).textContent = "DWARF";
dwarfButton.setAttribute("id", "dwarf");
You have a bit of chaining here, but ultimately you are setting the dwarfButton variable to the string "DWARF", rather then the DOM element you created.
Try this instead:
var dwarfButton = document.createElement("button");
dwarfButton.textContent = "DWARF";
dwarfButton.setAttribute("id", "dwarf");
chatbox.appendChild(dwarfButton);

Google Chrome crashes, doesn't recognize a variable as the name of a function

the following code works perfect of Firefox but crashes on Chrome, with the following error: Uncaught TypeError: Property 'pos' of object [object Object] is not a function
Here is the code, with comments:
var CantidadMenu = $('div[class^=container_menu_]').length;
var position = $("#menu_unidades").position();
var IzAdd = 0;
var w = $("#menu_unidades").width();
var h = $("#menu_unidades").height();
for (i=0;i<CantidadMenu;i++){
var pos = 'pos'+(i+1); //I create a variable that will hold a string like: pos1,pos2...
IzAdd = IzAdd+25;
function pos(div){ //on this line I use the variable I created, which crashes on Chrome
var estilo1 = $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
return estilo1;
}
pos('.container_menu_'+(i+1));
$('.container_menu_'+(i+1)).css({'z-index':297+i,'width':w,'height':h});
}
Here you define a function named pos:
function pos(div){ //on this line I use the variable I created, which crashes on Chrome
var estilo1 = $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
return estilo1;
}
console.log(pos) // function ....
Here you overwrite it with a string:
var pos = 'pos'+(i+1);
console.log(pos) // string....
You should name either the function or the string to something else.
PS: I know that in your code the order is reversed, but function declarations are hoisted to the top of the scope, so the JS interpreter "sees" them in the order i wrote them in: first function, then the string.
PSS: The crash is actually on this line:
pos('.container_menu_'+(i+1));
function pos(div) is the same as var pos = function(div)... (except the former is defined at the parse-time, and the latter at the run-time, but that's irrelevant for your code), so if you expected by defining that pos = 'pos1';, for example, you'd get function pos(div) to become function pos1(div), it won't.
It will just overwrite the pos variable, and it will no longer be a string, but a function.
To fix your code, write a single function at the top of your code, outside of the for loop, add another parameter to it (IzAdd) and make sure you fix the function calls appropriately.
The function should look something like this:
function pos(div, IzAdd){
return $(div).css({'left':IzAdd+25,'top':position.top+(IzAdd-25)});
}

Something is wrong in JavaScript object declaration

This code:
var doc = {
foldPrompt: function(folded) {
return folded ? "Click to unfold" : "Click to fold"
},
createFoldButtons: function() {
var prompt = foldPrompt(true); //The error is here
$("#ComparisonTable td.secrow").each(function(index, td){
$(td).prepend($('<img src="minus.gif" class="foldbtn" alt="'+prompt+'" title="'+prompt+'">'));
});
}
}
gives me an error: Undefined variable: foldPrompt
What am I doing wrong?
foldPrompt is not a variable; it's a property of doc, and you need an object reference to access properties of that object.
If someone calls doc.createFoldButtons(), then the this context variable will point at the same object that the doc variable does. So, replace foldPrompt(true) with this.foldPrompt(true).

Categories