Question

Suppose I have a number of red colored links, and want to add a click event to them such that when it fires, it sends HREF attribute of link to server (as an AJAX request), and on success, the link color will be changed to green. I want something like:

$$('a.red').addEvent(
    "click",
    function () {
        new Request.JSON({
            url: 'script.php', 
            onSuccess: function(){
                [the link wich is clicked].setStyle('color', 'green');
                return false;
            }
        }).get("url="+[url of the link]);
    }
);

Sorry if silly question. please edit title to some sensible one.

Was it helpful?

Solution

The problem here is that this inside the event handler is not the same as this inside the Request Class. So What usually is done is to change the reference to this in a new variable, for example var self = this.

After that you can use self.setStyle('color', 'green');

By the way, a suggestion, the best would be to have also a class for the green color and switch them by the time of the click.

So here is a code suggestion would be:

$$('a.red').addEvent("click", function (event) {
    var self = this;
    event.stop();
    new Request.JSON({
        url: 'script.php',
        onSuccess: function () {
            self.removeClass('red').addClass('green');
            return false; // I added event.stop(), presume that is what you meant. Do this line can be removed
        }
    }).get("url=" + self.href);
});

and using in the CSS something like:

.green {
    color: green;
}

Example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top