0

I have a HTML page from a tutorial that changes the page font size each time when different buttons are selected..Below is my html code and Js code.

<div id="switcher" class="switcher">
    <h3>Style Switcher</h3>
    <button id="switcher-default">
        Default
    </button>
    <button id="switcher-narrow">
        Narrow Column
    </button>
    <button id="switcher-large">
        Large Print
    </button>
</div>

Js:

$(document).ready(function() {
    $('#switcher-default').addClass('selected').on('click', function() {
        $('body').removeClass('narrow').removeClass('large');
    });

    $('#switcher-narrow').on('click', function() {
        $('body').addClass('narrow').removeClass('large');
    });


    $('#switcher-large').on('click', function() {
        $('body').removeClass('narrow').addClass('large');
    });

    $('#switcher button').on('click',function(){
        $('#switcher button').removeClass('selected');
        $(this).addClass('selected');
    })

});

Question: 1. When I click #switcher-default button, which event will be triggered first? Is it

$('#switcher-default').addClass('selected').on('click'

or

$('#switcher button').on('click',function(){
  1. What are the basic rules for event trigger?
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • If you're using Firefox or Chrome, you can go into Firebug view and run Audit then make your clicks to see which event is firing first. – Ally Jan 13 '14 at 19:53
  • You go from top to bottom in JS as in the HTML, meaning that the code in the top will fire first and after that it will fire the next one. – drip Jan 13 '14 at 19:57

2 Answers2

1

Try this:

 $(document).ready(function() { 

       $('#switcher-default').on('click', function() {
            $('#switcher button').removeClass('selected');
            $(this).addClass('selected');
            $('body').removeClass('narrow').removeClass('large');

        });

        $('#switcher-narrow').on('click', function() {
            $('#switcher button').removeClass('selected');
            $(this).addClass('selected');
            $('body').addClass('narrow').removeClass('large');
        });


        $('#switcher-large').on('click', function() {
           $('#switcher button').removeClass('selected');
            $(this).addClass('selected');
            $('body').removeClass('narrow').addClass('large');
        });
});
Tuhin
  • 3,335
  • 2
  • 16
  • 27
0

JQuery event handlers always execute in the order that they were bound.

someobject.click(somefunction)
someobject.click(someotherfunction)

In this example, somefunction will always be executed before someotherfunction when the event is called. If you want a way around this, see this other question.

For your particular example, see this jsfiddle. Determining how a framework works is most really easy when done through messageboxes.

Community
  • 1
  • 1
Jacklynn
  • 1,503
  • 1
  • 13
  • 23