Search code examples
calendaryuiyui3

How can I execute a callback on next/prev month click in YUI Calendar?


I am using a YUI3 Calendar, and I want to perform an operation when the month is changed. I would like to execute a callback when the next/prev month buttons have been clicked in the YUI Calendar. How can I do that?

I tried using A.one(), but it doesn't seem to work. Here is my current attempt:

<script src="http://yui.yahooapis.com/3.17.2/build/yui/yui-min.js"></script>
<div class="yui3-skin-sam">
    <div id="event-calendar"></div>
</div>
<script type="text/javascript">
    YUI().use('calendar', function (Y) {

        new Y.Calendar({
            contentBox: "#event-calendar",
            width: '230px',
            showPrevMonth: false,
            showNextMonth: false,
            date: new Date()
        }).render();

        A.one(".yui3-calendarnav-nextmonth").on('click', function (ev) {
            // ... execute code here
        });
    });
</script>

Solution

  • Your code seems to work for me, so I would assume that your problem is with this line:

    A.one(".yui3-calendarnav-nextmonth").on('click', function (ev) {
    

    You are selecting a single element by CSS class, but multiple elements could have the same class. So you are probably selecting another Node with the same class. You could probably get this code to work by being more specific with your CSS selector like so:

    A.one("#event-calendar .yui3-calendarnav-nextmonth").on('click', function (ev) {
    

    Now you are selecting an element with class="yui3-calendarnav-nextmonth" and a parent element with id="event-calendar". That should only select the next month button for your event-calendar.

    Here's a runnable example using alerts in the click listeners:

    YUI().use('calendar', function (A) {
    
        new A.Calendar({
            contentBox: "#event-calendar"
        }).render();
    
        A.one("#event-calendar .yui3-calendarnav-prevmonth").on('click', function (ev) {
            alert('prevMonth');
        });
    
        A.one("#event-calendar .yui3-calendarnav-nextmonth").on('click', function (ev) {
            alert('nextMonth');
        });
    });
    <script src="https://cdn.rawgit.com/stiemannkj1/0214fdc4cccaa77d6e504320cf70a571/raw/63d260364730fb067f103c00862c7e65685256df/yui-3.18.1_build_yui_yui-min.js"></script>
    <div class="yui3-skin-sam">
        <div id="event-calendar"></div>
    </div>

    See the YUI Calendar, Node, and YUI.one() API docs for more details. Also check out MDN's Information: Selectors article to learn more about CSS selectors.