Dynamically changing the size of a <div> element - javascript

I'm trying to resize a <div> when the function is called from this if statement. I know the if statement is working because when the function mTr() is called it works and I know the function myFun() works but for some reason the function myFun() isnt getting called.
if (window.screen.height==568) { // iPhone 4"
document.querySelector("meta[name=viewport]").content="width=320.1";
myFun("divId");
mTr();
}
function myFun(id)
{
var obj = document.getElementById(id);
if (obj)
{
obj.setAttribute("style", "height:300px;");
}
}
function mTr()
{
alert("Hello World!");
}

There are several reasons that myFun() wouldn't be getting called:
window.screen.height is not exactly 568
document.querySelector("meta[name=viewport]").content="width=320.1"; generates a script error that causes script execution to stop
There is some error before this code that causes execution to stop
Your code is executing too early before the DOM has been loaded and thus it can't find the relevant DOM elements.
The first thing to do is to examine your browser error console and see what script errors (if any) are reported.
The second thing to do it to set a breakpoint on the if statement in your javascript debugger (built into most browsers) and then step through each of the following statements to see what is happening.
You can also embed console.log("xxx") statements in your code to create a breadcrumb trail in the console to tell you what's going on.

I retested everything. I think I found your problem. You had an error in your code.
Error was here:
document.querySelector("meta[name=viewport]").content="width=320.1";
Instead, it should be:
document.querySelector("meta[name=viewport]").setAttribute('content', 'width=320.1');
Complete Javascript:
if (window.screen.height==568) {
document.querySelector("meta[name=viewport]").setAttribute('content', 'width=320.1');
myFun("divId");
mTr();
}
function myFun(id)
{
var obj = document.getElementById(id);
if (obj)
{
obj.setAttribute("style", "height:300px;");
}
}
function mTr()
{
alert("Hello World!");
}
You can test it out here:
http://jsfiddle.net/KwGwd/

Related

How to add 2 myFunctions?

I have added a myFunction code to my site. No problem, it works. Then I tried to add a second myFunction. The problem is, if I ad a second myFunction it doesn't work. It will only run succesfully when I use 1 myFunction. I tried everything to do, changed the name (myFunction2), people said me to do that but it doesn't work.
My question is now: How to add 2 myFunctions?
Script 1:
var myVar;
function myFunction(loader) {
myVar = setTimeout(showPage, 3000);
}
function showPage(loader) {
document.getElementById("loader").style.display = "none";
document.getElementById("myDiv").style.display = "block";
}
Script 2:
window.onscroll = function(scroller) {myFunction(scroller)};
function myFunction(scroller) {
if (document.body.scrollTop > 550 || document.documentElement.scrollTop > 550) {
document.getElementById("content").className = "slideUp";
}
}
You can't have more than one function with the same name. Try changing the second script to myScrollerFunction and when you call it, change it to myScrollerFunction as well.
No two functions can share the same name.
function UniqueFunctionName(parameters){
//put code here
}
UniqueFunctionName(startparameters); //not necessary
That is how to make a function.
function AnotherFunctionName(parameters){
//put code here
}
AnotherFunctionName(startparameters); //not necessary
That is how to make another function.
In your case this should be:
function myFunction1(){
//code in here
}
function myFunction2(){
//code in here
}
myFunction1(); // or not
myFunction2(); // or not
If it is like that the the specific code in the function needs to be debugged.
From what you have said i think that you just need to debug the code.
http://five.agency/javascript-debugging-for-dummies/
Learn to find and remove mistakes in your code and all will be easier.
If the code is flawless then the only other possibility is that it is not called.
To test for that insert this code like so:
function myFunction2(){
console.log('The function loads!');
//put code here
console.log('The function works!');
}
Save the code and open the webpage.
Open a debugger and search for the console.
If you see both messages then the code does not work the way it is expected.
If you see the first message and an error message then the code NEEDS debugging.
If you see neither messages then the code does not even load and you need to debug the input mechanisms/setInterval/setTimeout and/or parameters depending on the error message. If you have no input mechanisms/setInterval/setTimeout then add one or call the function directly from the code like shown in most of my code blocks above otherwise the code will never EVER load.
EDIT: parameter scroller is not defined. change 'function(scroller) {myFunction(scroller)};' to 'function(){myFunction2()};' and 'function myFunction(scroller) {' to 'function myFunction2(){'

Javascript TypeError is not a function issue

Run into a JavaScript issue that I can't understand. I'm making a JavaScript "class" that is supposed to draw some things on a canvas, and if the window gets resized, it's supposed to know how to resize the canvas on its own and fix orientation for the drawn objects.
Everything seems to work fine when I use this class from my own test html, but when I extracted my class into a separate .js file to be added as <script src="myclass.js"></script> for other people's usage, it starts throwing a "TypeError: this.func02 is not a function" error upon resize. This is annoying because this.func02 clearly is a function.
Also, there's a ticker constantly calling func03, and in the console I can clearly see logs being printed out periodically (those logs happen from func01, which is called by func03, in the exact same way that func02 calls it). Those logs keep working even after a TypeError showing up whenever I resize.
The JS:
function myClass() {
this.func01 = function() {
console.log("func1");
//do stuff
}
this.func02 = function() { //<- this doesn't work ???
this.func01();
//and do more stuff
}
this.func03 = function() { //<- this works ???
this.func01();
//stuff
}
window.addEventListener("resize", this.func02, false);
}
function useMe() {
objectOfMyClass = new myClass();
setInterval(tickerThatCallsFunc03ofMyClass, 50);
}
If anybody has any idea why this happens, please write stuff. I'm stumped on debugging this. I tried to remove all irrelevant code from my program, if you need more information post and I'll add it.
Note: the problem here isn't the keyword "this". Maybe it's part of the problem, but it's not all of it. The exact code works when it's in one file with the html, but doesn't work when it's added to the html with
this is inside of a function is referencing the function not the class to save a reference to the class and use that within a function:
function myClass() {
var myclass = this;
this.func01 = function() {
console.log("func1");
//do stuff
}
this.func02 = function() { //<- this doesn't work ???
myclass.func01(); //<- I get typeError on this call
//and do more stuff
}
this.func03 = function() { //<- this works ???
myclass.func01();
//stuff
}
window.addEventListener("resize", this.func02, false);
}
function useMe() {
objectOfMyClass = new myClass();
setInterval(tickerThatCallsFunc03ofMyClass, 50);
}

jQuery function not invoked from window variable

I need to show a primefaces dialog when my applet is closed, because there is a thread doing some stuff once it's finished i would like to hide the dialog from the page.
In order to do this i have used the liveConnect using netscape.javascript.JSObject.
this is working like a charm everything is alright.
The problem is the javascript functions are well invoked, but the dialog.show() function is not invoked.
Here is the code :
function doit1() {
$(window).ready(function() {
statusDialog.show();
});
}
;
function doit2() {
$(window).ready(function() {
statusDialog.hide();
});
};
window.callJS = function() {
console.log("we're here 1");
doit1();
console.log("its here1");
};
window.callJS1 = function() {
console.log("we're here 2");
doit2();
console.log("its here2");
};
these methods are called from the applet like this :
JSObject window = JSObject.getWindow(this);
window.call("callJS", null);
//do_some_thread_stuff();
window.call("callJS1", null);
And here is what's happening in the console :
we're here 1
its here1
we're here 2
its here2
So, what i'm really missing and what's preventing the dialog from showing.
Note : when i use chrome DevTools console to execute the doit() methods they're working fine but i get the undefined aftermath.
The problem was with threads, i was invoking JS methods before thread.start().
I've put the window.call("callJS", null); inside the thread and it's working fine.

JavaScript two onload functions

I am quite new to JavaScript programming and I'm trying to create some scripts that would save me time in maintaining one of my websites.
Now I have two functions in the same script that I'm calling from the head of my document and I'm trying to get them both to load at the same time with an onload event handler. I am doing that with window.onload command in my script (I want to make my script as unobtrusive as possible so I'm just calling the script in the header).
The problem is that only the first function loads and the second one doesn't. Can both functions be called with:
window.onload=function(){
function1();
function2();
}
or is there a different code I need to use to accomplish this?
I would really appreciate it if you could make your explanations as simple as possible as I am very new to JavaScript and programming in general.
P.S. If more than one function can't be loaded with onload, could you please explain to me why this is the case so I know in the future.
Ok, I see by the answers that my question probably left too much for assumption so here is the entire code of the functions I am trying to call (this is the script I am calling in the head of my html document):
I was trying to avoid putting the code here because my variables are written in Serbian language (as I am from Serbia), but I hope that you will still be able to look through it without much confusion.
In the code below I am calling at the bottom of the script two functions (lista() and ostale()) and the moveover() function is just a helper function called by the lista() function.
In essence the first one (lista()) lists through all elements of div "boje" (in English translated to "colors") and depending on the color the user hovers their mouse over, the background image changes. It also adds a few attributes to those image elements that the user is supposed to hover over.
The second one (ostale() (Translated to English "others") is supposed to only add attributes to the rest of the color images that are not supposed to do anything if the user hovers over them.
But when I open the page in localhost it doesn't show in Firefox's inspect element that any attributes have been added to the images within the div "ostale".
function lista()
{
var boje = document.getElementById('boje');
var broj = boje.childNodes.length;
for(i=1; i<broj; i++)
{
var stavka = boje.childNodes.item(i);
stavka.setAttribute("id", i);
stavka.setAttribute("onmouseover", "moveover(src)");
stavka.setAttribute("alt", "Boja");
stavka.setAttribute("class", "boja");
stavka.hspace="2";
stavka.height="23";
}
}
function moveover(adresaBoje)
{
var izvor = adresaBoje;
var slika = izvor.slice(0, izvor.length-4);
var pocetak = "url(";
var ekstenzija = ".jpg)";
var novaSlika = pocetak.concat(slika, ekstenzija);
document.getElementById('slika').style.backgroundImage=novaSlika;
}
function ostalo(){
var ostaleboje = document.getElementById('ostale');
var ostalebroj = ostaleboje.childNodes.length;
for(n=1; n<ostalebroj; n++)
{
var ostalestavka = ostaleboje.childNodes.item(n);
ostalestavka.setAttribute("alt", "Boja");
ostalestavka.hspace="2";
ostalestavka.height="23";
}
}
window.onload=function(){
try
{
lista();
ostalo();
}
catch(err)
{
alert(err);
}
}
After I try to load the page it alerts me with an error: "TypeError: stavka.setAttribute is not a function".
This is the html document I am trying to manipulate:
<div id="slika" style="background-image: url(images/nova_brilliant/1.jpg)">
</div>
<div id="tekst">
<h1>Nova Brilliant</h1>
<div id="sadrzaj">
<p>Pređite mišem preko željene boje da biste videli kako izgleda ova kuhinja u toj boji:</p>
<div id="boje">
<img src="images/nova_brilliant/1.gif"><img src="images/nova_brilliant/2.gif"><img src="images/nova_brilliant/3.gif">
</div>
<p>Ostale dostupne boje:</p>
<div id="ostale">
<img src="images/nova_brilliant/4.gif"><img src="images/nova_brilliant/5.gif"><img src="images/nova_brilliant/6.gif">
</div>
</div>
</div>
I ran into the same problem. I came across a couple of help but this one was easy to understand and it worked for me:
window.addEventListener("load", func1); window.addEventListener("load", func2);
just like #Quentin You can read more about it here
Yes you can. However, if the first goes wrong, the second won't fire.
Use this to catch errors:
try { //try executing the functions
function1();
function2();
}
catch(error) { // If there's an error
alert(error); // alert the error.
}
It is a good practice to put try and catch when experimenting with javascript.
Edited: Sorry i confused childNodes[] with childNodes.item().
By the way, I tried something like this, and it works just fine:
<head>
<script>
window.onload = function() {
div = document.getElementById("someDiv");
length = div.childNodes.length;
first();
second();
}
function first() {
for(var i=0;i<length;i++) {
var set = div.childNodes.item(i);
set.setAttribute("name", "span " + (i+1));
}
}
function second() {
for(var i=0;i<length;i++) {
name = div.childNodes[i].getAttribute("name");
console.log(name);
}
}
</script>
</head>
<body>
<div id='someDiv'><span id='span1'></span><span id='span2'></span></div>
</body>
UPDATE: I found the error:
Actually there's nothing wrong with your code. It works just fine, however, the last item of boje is empty space, which means, a text node. That's why the error keeps showing up. Change for(i=1; i<broj; i++) with for(i=1; i<broj-1; i++) and everything should be good.
Can both functions be called with
Yes. If you add event handlers by assigning to DOM properties, then you can only assign a single function to each but that function can call other functions.
However, if you do that and the first function throws an error then the second function won't fire at all. It will also discard the context and arguments, as they won't be passed to the called functions.
You could work around those problems like so:
window.onload=function(){
try {
function1.apply(this, arguments);
} catch (e) { }
try {
function2.apply(this, arguments);
} catch (e) { }
}
or is there a different code I need to use to accomplish this?
You should use addEventListener instead. That avoids the need to fiddle with apply, and protects you from errors being thrown. See the MDN events documentation for more details.
window.addEventListener('load', function1);
window.addEventListener('load', function2);

JavaScript event handlers -why no alert?

I'm a newbie at JavaScript trying to learn event handlers. Looking at this fiddle http://jsfiddle.net/mjmitche/uV4kv/ can anyone tell me why the pop up is not appearing when the link is clicked?
I've also copied the code below
click me
function addEventHandler(oNode, sEvt, fFunc, bCaptures){
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+sEvt, fFunc);
else
oNode.addEventListener(sEvt,fFunc,bCaptures);
}
function onLinkClicked(e) {
alert("you clicked the link");
}
function setUpClickHandler(){
addEventHanlder(document.getElementById('clickLink'), "click", onLinkClicked, false);
}
addEventHandler(window,"load",setUpClickHandler,false);
There are basically three problems:
You have some typos, e.g. "Hanlder" instead of "Handler" and "Sevt" instead of "sEvt".
The code is already run after page load, so the event handler you add to window will never be called. Change in jsFiddle from onLoad to no wrap (head).
You "IE detection" does not work. I get this error in Chrome:
Uncaught TypeError: Object http://fiddle.jshell.net/_display/# has no method 'attachEvent'.
Better would be to test whether the function window.attachEvent exists. I also think that window.event is only available when an event is raised.
If this is corrected, your code will run (DEMO).
Further notes:
Testing which method is supported (i.e. attachEvent or addEventListener) on every call of your function is unnecessary. It won't change during the life of the page. Better is to test only once at the beginning. Example:
var addEventHandler = (function() {
if(window.attachEvent) {
return function(oNode, sEvt, fFunc) {
oNode.attachEvent("on"+sEvt, fFunc);
};
}
else {
return function(oNode, sEvt, fFunc, bCaptures) {
oNode.addEventListener(sEvt,fFunc,bCaptures);
};
}
}());
This assigns a function the supported function to addEventHandler.
A couple of problems:
You have a recurring typo, "Hanlder" instead of "Handler". There are at least two, one where you do your setUpClickHanlder (sic) function, and one within it (addEventHanlder).
Also, you have "Sevt" where you mean "sEvt". (JavaScript is case sensitive.)
Let tools help you. Use a browser that gives you a console showing errors. Use a debugger for single-stepping through code, looking at variable values at runtime with inspectors, etc.
Your addEventHandler needs adustment:
function addEventHandler(oNode, sEvt, fFunc, bCaptures) {
oNode.attachEvent ? oNode.attachEvent ("on" + sEvt, fFunc) :
oNode.addEventListener (sEvt, fFunc, bCaptures);
}
It is in event handlers themselves that you need to check for window.event

Categories

Resources