JamesLKingsley
JamesLKingsley

Reputation: 71

Javascript - Uncaught ReferenceError - Code seems perfect?

Here's how I'm calling my JS:

<a href="javascript:void(0)" class="FCChatControl" onClick="toggleChatControl('cwa#item.OwnerID#')"></a>

"#item.OwnerID#" is a variable from a loop containing an ID. So the element I want to change the CSS for should look like: "cwa123" or some other number for the id...

Here's my JS:

$(document).ready(function() {
    function toggleChatControl(id){
        var wnd = document.getElementById(id);
        if (wnd.style.marginBottom == '-1px') {
            wnd.style.marginBottom = '-236px';              
        } else {
            wnd.style.marginBottom = '-1px';
        }
    }
});

I ain't got a clue, it gives me the "not defined" error...

Upvotes: 0

Views: 77

Answers (1)

adeneo
adeneo

Reputation: 318182

Out of scope, remove the document ready wrapper

function toggleChatControl(id){
    var wnd = document.getElementById(id);
    if (wnd.style.marginBottom == '-1px') {
        wnd.style.marginBottom = '-236px';              
    } else {
        wnd.style.marginBottom = '-1px';
    }
}

Every function creates a new scope, the global scope is window, and that's the scope used for inline javascript.

Inside $(document).ready(function() { ... }); the scope is changed (to document) so the function is out of scope for the inline handler.

An even better approach would be to use a proper event handler

$('.FCChatControl').on('click', function() {
    toggleChatControl('cwa#item.OwnerID#');
});

Upvotes: 3

Related Questions