Search code examples
jqueryjquery-eventsgetuikit

Can't read custom UIKit events


UIKit has several custom events that are fired. For example, when switching tabs, a change.uk.tab event is fired (https://getuikit.com/docs/tab.html). The problem is I can only read the event if I prefix JQuery's "$" with UIKit.$. It's as if UIKit's jQuery $ is returning a different object.

So for example, this will work:

UIkit.$('#tabs').on('change.uk.tab', function(e, active, previous) {
    console.log("uk tab changed: " + active.context.id);
});

Here's the html:

<ul id="tabs" class="uk-tab" data-uk-tab >
    <li id="tabPage1" class="uk-active"><a href="">tabPage1</a></li>
    <li id="tabPage2"><a href="">tabPage2</a></li>
    <li id="tabPage3"><a href="">tabPage3</a></li>
</ul>

However, if I were to remove the "UIkit." and just use the "$" object alone:

$('#tabs').on('change.uk.tab', function(e, active, previous) {
    console.log("uk tab changed: " + active.context.id);
});

then I wouldn't see the change.uk.tab event. (That is, the console.log line is never executed.) Why is this? What's the difference between "UiKit.$" and just "$"?


Solution

  • As you can see in:

    doc:

    `<!-- Element within a modal, switcher or dropdown -->

    <div id="myelement" data-uk-check-display>...</div>

    <script>

    $("#myelement").on('display.uk.check', function(){ // custom code to adjust height etc on show }); </script>`

    you can avoid UIkit.$('#tabs') and use directly $('#tabs').

    You can see in you console UIkit is an object containing a reference to $ or better jQuery.

    The snippet:

    $(function () {
      console.log('UIkit.$.fn.jquery: ' + UIkit.$.fn.jquery);
      console.log('$.fn.jquery: ' + $.fn.jquery);
      $('#tabs').on('change.uk.tab', function(e, active, previous) {
        console.log("uk tab changed: " + active.context.id);
      });
    });
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.1/css/uikit.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.1/js/uikit.min.js"></script>
    
    
    <ul id="tabs" class="uk-tab" data-uk-tab >
        <li id="tabPage1" class="uk-active"><a href="">tabPage1</a></li>
        <li id="tabPage2"><a href="">tabPage2</a></li>
        <li id="tabPage3"><a href="">tabPage3</a></li>
    </ul>