'Can´t find variable' when using onclick [Solved]

'Can´t find variable' when using onclick [Solved]
0

#1

Hi, i’m triying to change the weather value from celcius to farenheit, to do this I´ve created to links each one calling a diferent function that hides the other link and updates the content on the weather div.

However, when I click the button the console says ‘can´t find variable celsius’, as you can see on this codepen http://codepen.io/miguelopezv/pen/pbeZoL [Test it in safari to see it works].

Any idea why this is happening?


#2

The problem lies with your event handler assignments on line 8 and 9. Because you’re wrapping your JavaScript code in a closure (very good), the HTML doesn’t have access to the functions cel and far. I suggest assigning the event handlers via JavaScript instead.


#3

The problem is that you are executing the code the moment window loads. It fires off once and does nothing further than that. All the methods in it are private to the anonymous function and cannot be accessed from the outside. There are several way to deal with it. One is as @PortableStick suggested. However, it is simply untrue that you can’t access these events from the html itself. What you need is a factory function. A factory function is still a closure but it provides concatenative inheritance. This medium article here can explain it far better than I can:

And here is my tic tac toe game that uses these methods. It still needs a bit of polish but it is fully functional and hopefully the code is not terribly obnoxious :smiley:

Finally, window.load is only necessary when you upload your script files before the DOM has finished loading (which normally you shouldn’t do).


#4

I dig what you’re saying, but my exact words were "doesn’t have access to the functions cel and far". That’s totally different from “you can’t access these events from the html itself”. Great article, though.


#5

I always advise to avoid inline event handlers on the HTML.

I prefer to use it on the JS file/script tag:

var myElement = document.getElementById('theId');

myElement.addEventListener('click', function(event) {
  console.log('My HTML element was clicked, woot woot!);
});

The browser API provides a hell lot of event handlers like keyup for input boxes or onMouseOver for pretty much everything, it also provides events for forms (I.E submit).


#6

I see that now. That’ s what I get from writing responses when I’m half asleep. Anyway, sorry for that.


#7

Sorry for the late reply, I had a work-related travel and didn’t had my Laptop with me. I used @luishendrix92 solution [and also remove the window.onload as @mkarabashev suggested]and is working like a charm. thank you so much for your help!! now to the next Project!!