How do you stop a function from being executed and only execute on click in mootools

StackOverflow https://stackoverflow.com/questions/22835174

  •  26-06-2023
  •  | 
  •  

Question

I'm new to Mootools and I have found that I have to use the click element but I'm not 100% sure where I am meant to put it in the below code:

function setInStockOption (labels, e) {
    active = false;
    labels.some (function (item,index) {
        if(item.hasClass ('selected')) {
            if(item.hasClass ('unavailable')) {
                item.removeClass('selected');
                item.addClass ('unselected');
                active = true;
            } else {
                return true;
            }
        }
        if(active) {
            if (!item.hasClass ('unavailable')) {
                e.target = this;
                item.fireEvent ('click', e);
                active = false;
                return true;
            }
        }
    });
}

window.addEvent('load', function(e) {
    var labels = $$('div.option-radios label.radio');

    setInStockOption(labels, e);
});

I basically need to add the class selected on click instead. At the moment this script is adding the selected class to the first child of Radio in the html and then when you click on others it'll add the class selected. I basically want all the classes to be unselected when the page loads .

Any ideas?

Was it helpful?

Solution

You'll want something like this:

window.addEvent('domready', function(e) {
    $$('div.option-radios label.radio').each(function(label, i) {
        label.addEvent('click', function(event) {
            event.target.toggleClass('selected');
        });
    });
});

Note that this uses the Array.each method instead of Array.some. The latter doesn't do what you expect. It then registers a click event on every label which simply toggles the selected class on the event target.

Then you can add other initialization code to the each loop and more logic to the click event handler.

I also used the domready event which is usually preferred over load since it fires earlier.

Here's a fiddle to play around with.

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