$w running before page onReady?

Hello,
Newbie here. Could someone please let me know what I am doing wrong here. I am sure its a simple fix.
Error: The element selector function (usually $w) cannot be used before the page is ready

$w.onReady(function () {
 //TODO: write your page related code here...
});

let slideOptions = {
 "duration":   500,
 "delay":      100,
 "direction":  "top"
};

let menuBox = ("#boxJC");

export function buttonJC_mouseIn(event){
    menuBox.show("slide", slideOptions);
 
}
export function boxJC_mouseOut(event) {
    menuBox.hide("slide", slideOptions);
 
}
export function boxJC_mouseIn(event) {
    menuBox.show();
 
}
export function buttonJC_mouseOut(event) {
    menuBox.hide(); 
 
}

Hi Blake,

It’s good to declare page level “global” variables at the top of the page. To reference or access an element requires that it be rendered or loaded at that time. That’s the purpose of the page onReady function.

let menuBox = "";
let slideOptions = {
 "duration":   500,
 "delay":      100,
 "direction":  "top"
};

$w.onReady(function () {
    menuBox =("#boxJC");
});

Hi Anthony,

Thank you very much!
I don’t expect a full coding course here haha. but if you have the time would you be able to explain in a little more detail what you have done here? or point me to some info on these principles. I think I understand but not quite sure haha

if not, no worries. Really appreciate the help/fix :slight_smile:

Fixed code:

let menuBox = ("");
let slideOptions = {
 "duration":   500,
 "delay":      100,
 "direction":  "top"
};


$w.onReady(function () {
    menuBox = $w("#boxJC");
});

export function buttonJC_mouseIn(event){
    menuBox.show("slide", slideOptions);
 
}

export function boxJC_mouseOut(event) {
    menuBox.hide("slide", slideOptions);
 
}

export function boxJC_mouseIn(event) {
    menuBox.show();
 
}

export function buttonJC_mouseOut(event) {
    menuBox.hide(); 
 
}

So … declaring variables at the top of the page means that they have scope or are available to be accessed in any function on the page. At times that is exactly what you want.

The onReady event executes after all of the elements on the page are fully loaded or rendered. If you have free code, code that is not inside any function that is referencing an element and not loaded yet, you will get the element selector function error. Put that same code inside of the onReady, and you can be sure that the element is actually on the page and ready to be accessed.