2

Now I would expect this function to only run when clicking on a <a data-popup="true"></a> element however it's running on every <a> click.

(function($) {
    $(document).ready(function() {
        $('a').data('popup', 'true').click(function(e) {
            console.log($(this).data('popup'));
            e.preventDefault();
        });
    });
})(jQuery);

2 Answers 2

2

The .data() method get/sets data associated with the element; it doesn't filter the elements like you are expecting. You are actually setting a key/value pair of data on all the anchor elements and then attaching an event listener to all the anchor elements. In other words, when you set data with the .data() method, the original jQuery object is returned (which means that the .click() method is still attaching a click event handler to all the originally selected anchor elements).

You are looking for an attribute selector. In this case, the selector a[data-popup="true"] will select anchor elements with a data-popup attribute value of true.

$('a[data-popup="true"]').click(function(e) {
    console.log($(this).data('popup'));
    e.preventDefault();
});
Sign up to request clarification or add additional context in comments.

Comments

0

Below code will attach data for all existing a link in the code.

$('a').data('popup', 'true').click(function(e) 

you may try this:

<a id="popid" data-popup="true"></a>

(function($) {
    $(document).ready(function() {
        $('#popid').click(function(e) {
            console.log($(this).data('popup'));
            e.preventDefault();
        });
    });
})(jQuery);

To check popup for all a link, you may try below.

(function($) {
    $(document).ready(function() {
        $('a').click(function(e) {
            if ($(this).data('popup')){
                console.log($(this).data('popup'));
                e.preventDefault();
            }
        });
    });
})(jQuery);

or

$('a[data-popup="true"]').click(function(e) {
    console.log($(this).data('popup'));
    e.preventDefault();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.