Good afternoon everyone;
I am working with processingjs and I realize one characteristic feature of processingjs;
I have a sketch file called mysketch1.pde and inside of my sketch I just declared int x=5; for test purposes. Thus, mysketch1.pde includes a method called getX() which is a getter for x value.
Lets say, I want to reach this value and print it on my web page. If I write my java script like that I have a problem;
<script type="text/javascript">
var mysketch = Processing.getInstanceById("mysketch1");
if(mysketch==null){
window.alert("it is null");
}
else
window.alert(mysketch.getX());
</script>
In this code mysketch variable returns null all the time. (I am including my sketch before javascript on the head section)
However, If I put a button to my web page and call the same code as function it works perfectly;
<script type="text/javascript">
function click(){
var mysketch = Processing.getInstanceById("mysketch1");
if(mysketch==null){
window.alert("it is null");
}
else
window.alert(mysketch.getX());
}
</script>
<button type="button" onclick="click()">place</button>
I assume this stuation happends because somehow javascript works before my .pde file is loaded.I would like to display value of X after .pde is loaded automatically. Do you know how can I cope with this problem?
Regards,
You should put your code on the window.onload event:
window.onload = function () {
var mysketch = Processing.getInstanceById("mysketch1");
if (mysketch === null) {
window.alert("it is null");
} else {
window.alert(mysketch.getX());
}
}
One way to get around this would be to poll the getX() function until the sketch becomes ready, like setting a timeout to wait until the variable is not null. This approach could also be used to check when the sketch in general is ready, like having a function isReady(){ return true;} and waiting until it is not null to run the rest of your script.
Related
I want to execute a piece of C# code whenever I run a JavaScript function but it doesn't seem to behave the way I want it to here is an example:
Let's say that I have a variable property int Counter {get; set; } in the Model that I want to increment every time I run a JavaScript function:
<script type="text/javascript">
function MyFunction(){
//Do some stuff
#{Model.Counter++;}
}
</script>
What is really happening is that when the page loads #{Model.Counter++;} is getting executed regardless of not being called from the function.
And whenever I run the function again its ignoring it completely.
Meaning this piece of code #{Model.Counter++;} is getting executed once when the page loads and never again.
How do I fix that and make it execute every time I run the function?
You can use ActiveX control to execute Compiled program. but you should know that your html code only will work in IE.
You will have to create a hidden field for model.counter somewhere inside a view form
<input type="hidden" id="modelCounter" asp-for="Counter" value="#Model.Counter" />
after this you can change Counter using javascript
function MyFunction(){
//Do some stuff
var counter=$("#modelCounter").val();
counter++;
$("#modelCounter").val(counter);
}
I don't think what you want is possible (maybe with Blazor? - but that is WebAssembly).
Instead you can assign a new javascript variable to your model property.
E.g.:
<script type="text/javascript">
function MyFunction(){
//Do some stuff
let counter = #{Model.Counter};
counter++;
// Do some stuff with counter
}
// When you are done, post the counter back if needed on server side
</script>
Try This
#{
var a=Model.Counter;
}
do this outside the script
and inside the function or script
do
#a++;
or
var c = #a;
c++;
hope it works
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);
I dont know a whole lot about javascript and i was wondering if this script would run or do i need to put the "if statement" inside some kind of onPageLoad function to run this? Please help.
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
Sure it would run -- but it would depend on something else having run first so that time has a value.
For example, this would work (even though it's bad practice because it sets a property on window):
<script>
time = 10;
</script>
<script>
if (time<20)
{
alert("Hello World!");
}
</script>
You would also find it impossible to guarantee that any variables you need for temporary processing are kept out of the reach of other scripts. To overcome this limitation, you can (and except in the most trivial of sites, should) wrap the code inside an anonymous function that is invoked on the spot:
<script>
(function() {
// your code here
})();
</script>
If you want to access DOM Elements you have to put the script tag at the end of the page. Or you use something like onload of the body tag (or an equivalent funciton in JS framework)
It would run, realize time is undefined, generate an error and halt operations from that point on.
If "time" is seted on server side, so, you may write onload property body dinamically like this:
<body onload="functionName(<?php echo()?>)">
and then:
<script type="text/javascript">
function functionName(time) {
if(time < 30) { ... }
}
</script>
Adopted some javascript code that I'm rearranging into smaller files to make it more managable; I'm never been a full-time javascript engineer but have worked with it for awhile but don't feel super comfortable with it.
I have an object literal that handles most of our controller level activities for our site. We've rearranged the code and put it in different files but there's one specific object where I'm getting an undefined error. Looking at the load order of the files, it comes in before the jQuery piece. Also wrapping this object literal in another jQuery onready wrapper fixes the problem. If I check via somethign like this:
if (typeof arc.event_handler === "undefined"){
alert("something is undefined");
}else{
alert("something is defined");
}
then with jQuery onready wrapping, it is defined but without it is undefined. Like (I know that this code will work either with or without the jQuery onload)
// file-1.js
var arc={};
$(document).ready(function(){
arc.event_handler={
do_something: function(){
alert('do something');
}
}
});
and then later in different file
// later in load order z-file.js
$(document).ready(function(){
if (typeof arc.event_handler === "undefined"){
alert("something is undefined");
}else{
alert("something is defined");
}
$('.some').on('click',function(){
arc.event_handler.do_something();
});
});
I'm a little bit at a loss what could causing this behavior. My understanding is that even if an external file, the part in the jQuery onready should essentially cause it to wait until these other pieces are loaded. I'm probably not getting something really simple but wanted to see if there were any ideas about what next to look at next?
thx in advance
<script type="text/javascript" src="/first.js"></script>
<script type="text/javascript" src="/second.js"></script>
first.js:
arc = {
event_handler: {
do_something: function(){
alert('do something');
}
}
};
second.js:
$(document).ready(function(){
$('.some').on('click', arc.event_handler.do_something);
});
I am having trouble with some JavaScript running before the page is completely rendered in IE 6 (maybe other versions too but just testing IE6 for now. Firefox seems to be OK). I can get around this by calling the js on window.onload like this:
window.onload = function(){doIt();}
However, my concern is the fact that I will overwrite anything else that may already be in window.onload. The code will be used as part of a library so I can not guarantee that window.onload will not be set somewhere else by someone else. I would rather append my function to the onload event like this:
window.onload += function(){doIt1();}
window.onload += function(){doIt2();}
But when I do so, only doit2() is called. Is there a way to register an event handler for when the page is fully rendered? My second thought would be to just put my code in a loop checking to make sure all my objects exist before running. But I am scared that this could potentially lockup the browser.
Just for some background info, my code is hiding/showing iFrames. I know that I can use the iFrame's onload attribute but I need all of the iFrames to be fully loaded before calling the code.
Any thoughts from the community? Thanks in advance for you input.
Use this generic addLoadEvent function...
function addLoadEvent(func) {
if(typeof window.onload != 'function')
window.onload = func;
else {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad) oldLoad();
func();
}
}
}
This essentially queues up functions to be executed. It never overwrites a previously assigned handler. Sample usage below...
addLoadEvent(function() { alert("One!"); });
addLoadEvent(two);
function two() {
alert("Two!");
}
I want to mention that libraries like jQuery take care of known issues like this for you.