this object and its counterpart within a click event

I created my own JavaScript class and tried to use jQuery's $(this) and object-this in a click event.

jQuery's $(this) works fine, but the object-this is not defined.

http://jsfiddle.net/j33Fx/2/

var myclass = function(){

    this.myfunction = function(){
        alert('myfunction');
    }

    this.buttonclicked = function(){
        alert('buttonclicked');
    }

    this.writeout = function(){
        var buttoncode = '<button class="mybutton">click</button>';
        $('body').append(buttoncode);

        $('.mybutton').click(function(){
            alert('Button: '+$(this).attr('class'));
            this.buttonclicked(); 
        });

        this.myfunction();
    }

}


var x = new myclass();
x.writeout();

When I click the appended button, I get an alert with the classname of the Button, but my function "this.buttonclicked" seems not to be a function.

Any suggestions?

Answer №1

This denotes the element that triggered the event in the event handler. To prevent any confusion, you can store the current object in a separate variable for future use.

Implement it like this:

this.displayButton = function(){
    var buttonHTML = '<button class="mybutton">click</button>';
    $('body').append(buttonHTML);

    var _self = this; //store current object

    $('.mybutton').click(function(){
        alert('Button: '+ $(this).attr('class')); //In this context, 'this' refers to the clicked element.

        _self.buttonClicked(); //Access cached object
    });

    this.myFunction();
}

Updated Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering undefined data when trying to access returned JSON data through jQuery Ajax

Utilizing the MVC approach, within my javascript code, I am encountering a discrepancy. Upon using console.log(data.msg) in the success function, the desired result is achieved. However, when attempting to employ $('#res').text("".data.msg), an ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

Check if a key exists in an array that contains sub-arrays using the function array_key_exists

I am encountering an issue with a function. My goal is to include all pages, but the problem is that not all pages are named like the parameter $_GET['page']. For example, if I call index.php?p=accueil, it should redirect to php/home.php. Anoth ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

The final value is always returned by jQuery's each method

Is there a way to prevent the .each() function from selecting the last value every time it runs? var items = ["item1", "item2", "item3"]; $("#list li").each(function() { var addedClass; if ($(this).hasClass("one")) { addedClass = "red"; } else ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...

Is there a way for me to display a gif similar to 9GAG on my

I'm looking to implement a feature on my website that allows me to pause and play a gif, similar to the functionality on 9gag. Can anyone provide guidance on how I can achieve this? I understand that I need to use both .jpg and .gif files, but my at ...

Ways to prevent other users from clicking or modifying a particular row

I have a data table in my project that will be accessed by multiple users simultaneously. My requirement is that once a row is selected and edited by one user, it should become unclickable for other users who are also viewing the same page or data table. ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

Load ajax content dynamically based on the updated URL

Exploring ajax for the first time and having some issues. Currently, I am retrieving text from files based on the URL. This is how it's set up: var home_url = "blahblah/index.html#home"; var test_url = "blahblah/index.html#test"; $(document).on("c ...

Interconnected Dropdown Menus

I've implemented the cascading dropdown jQuery plugin available at https://github.com/dnasir/jquery-cascading-dropdown. In my setup, I have two dropdowns named 'Client' and 'Site'. The goal is to dynamically reduce the list of si ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Using brush strokes to create a unique design on the canvas page

Currently, I am working on implementing a brush-like effect on a web page. The task involves providing multiple patterns/textures in the background and allowing users to drag their mouse to create the pattern effect on the page. If you want to see the st ...

The submit function in Jquery is not functioning properly within the success callback of an Ajax request

After successfully submitting a form in AJAX using POST, I receive a new form that needs to be automatically submitted in jQuery. However, for some reason, the .submit() function seems to be ignored and I can't figure out why. I've tried adding ...

Creating a dropdown menu by specifying specific names within an object

I am in the process of setting up a dropdown menu for all 50 states using an object that contains state names as attributes. Here's an example: window.LGMaps.maps.usa = { "paths": [ { "enable": true, "name": "Alaba ...

Choose a dynamically generated html element without having to click on it

I've been looking for a way to target a dynamically-generated element (specifically a div with the class "date") using jQuery. While I keep finding references to the .on('click') method, it appears that this only selects the div once the pag ...

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...