0

I have 2 methods, one is internal method and the other one is instance method, When I'm calling my internal function(onkeydown="javascript:return checkChatBoxInputKey();") it works great,
But when I'm trying to activate the onclick event (onclick="this.CloseChatBox();) I get the following error:

0x800a01b6 - Microsoft JScript runtime error: Object doesn't support property or method 'CloseChatBox'

Here is my code:

function ChatBox(){
    // Methods
    this.CloseChatBox = ChatBox.CloseChatBox;

    // Adding new chat box to page
    $(" <div />").attr("id", "chatbox")
    .html('<div class="chatboxhead">' +                                                    
          '<a href="javascript:void(0)" title="Close chat box" onclick="this.CloseChatBox();">X</a>' + // This line fails to work
                    '</div>' +
                    '<div class="chatboxbody">' +
                            '<textarea onkeydown="javascript:return checkChatBoxInputKey();"></textarea>' +
                    '</div>')
    .appendTo($("body"));

    $("#chatbox_" + this.CallId).show();

    return true;}

function checkChatBoxInputKey(){
    alert("checkChatBoxInputKey");}

ChatBox.CloseChatBox = function (){
    alert("CloseChatBox");}

What can I do?

1
  • $(" <div />").attr("id", "chatbox"), make sure that you don't have multiple elements with the same ID. Commented Jan 14, 2013 at 14:48

1 Answer 1

1

In the onclick, this is the <a> tag itself not whatever it was in the ChatBox function.

So, you're getting the error because <a> tags don't have a CloseChatBox method.

I highly suggest not using attributes for event binding. Use actual event handlers. Add a class to the <a> tag, then bind an event to it using jQuery.

HTML:

<a href="javascript:void(0)" title="Close chat box" class="closeChatBox">X</a>

JavaScript (placed outside of the ChatBox function, inside a $(document).ready):

$('a.closeChatBox').click(function(){
    ChatBox.CloseChatBox();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, so how can I call my function?
I don't think that will work if there are multiple ChatBox instances. In that case, I'd rewrite ChatBox as a jQuery plugin.
@bfavaretto: That's probably a better idea. I guess you could pass the element to the CloseChatBox function also. ChatBox.CloseChatBox(this);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.