Tuesday, February 28, 2017

HTML 5 Custom Data Attributes using jquery

In this post I will show, how to get HTML 5 Custom Data Attribute values using jquery.
Previously I had shown How to...
MVC:
Output:














Copy & paste the below code into notepad and save as html file.

<html>
<header>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="alert.js" type="text/javascript"></script>

</header>
<form class="form-horizontal" role="form">
<body><br><br><br><br>
<div class='container'>
<center>
<h4 class='form-control'>Get value of HTML 5 Custom Data Attributes using jquery</h4>
</center>

<a href="javascript:void(0)"  class="button btn btn-primary" data-position="top-right" data-info='{"foo":"bar"}'>
data-position = "top-right" data-info = '{ "foo" : "bar" }'</a>
<br><br>
<a href="javascript:void(0)"  class="button1 btn btn-primary" data-position="top-left" data-info='{"foo":"bar", "goo":"ABC"}'>
data-position = "top-left" data-info = '{"foo" : "bar", "goo" : "ABC" }'</a>


</div>

</form>
</body>

<script type="text/javascript">

$(document).ready(function(){
 var Message = 'Default Message';
 
 $('.button').click(function(){
  
  var link = $(this);
  Message = link.attr('data-info') +', Position :  '+link.data('position');
  msg(link.data('position'));
 });
 
 $('.button1').click(function(){
  
  var link = $(this);
  Message = 'foo : '+link.data('info').foo +', goo : '+link.data('info').goo +', Position : '+link.data('position');
  msg(link.data('position'));
 });
 
 function msg(position)
 {
   $.alert(Message, {
                title: 'jQuery Script',
                closeTime: 30000,
                autoClose: true,
                position: [position],
                withTime: true,
                type: 'success', //info, warning, danger, success
                isOnly: false //Multiple instances
            });
 }

});

</script>
</html>
To display alert message use below code and save as alert.js. Credit goes to original developer

(function ($) {
    $.alert_ext = {
        
        defaults: {
            autoClose: true,
            closeTime: 5000,   // 1000
            withTime: false, // ...10
            type: 'danger',  
            position: ['center', [-0.42, 0]],
            title: false, 
            close: '',   
            speed: 'normal',
            isOnly: true,
            minTop: 10, //Top
            onShow: function () {
            },  
            onClose: function () {
            }  
        },

        tmpl: '<div class="alert alert-dismissable ${State}"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4 style="white-space: nowrap;">${Title}</h4><p>${Content}</p></div>',

        init: function (msg, options) {
            this.options = $.extend({}, this.defaults, options);

            this.create(msg);
            this.set_css();

            this.bind_event();

            return this.alertDiv;
        },

        template: function (tmpl, data) {
            $.each(data, function (k, v) {
                tmpl = tmpl.replace('${' + k + '}', v);
            });
            return $(tmpl);
        },

        create: function (msg) {
            this.alertDiv = this.template(this.tmpl, {
                State: 'alert-' + this.options.type,
                Title: this.options.title,
                Content: msg
            }).hide();
            if (!this.options.title) {
                $('h4', this.alertDiv).remove();
                $('p', this.alertDiv).css('margin-right', '15px');
            }
            if (this.options.isOnly) {
                $('body > .alert').remove();
            }
            this.alertDiv.appendTo($('body'));
        },

        set_css: function () {
            var alertDiv = this.alertDiv;

            alertDiv.css({
                'position': 'fixed',
                'z-index': 10001 + $(".alert").length
            });

            // IE6
            var ie6 = 0;
            if ($.browser && $.browser.msie && $.browser.version == '6.0') {
                alertDiv.css('position', 'absolute');
                ie6 = $(window).scrollTop();
            }

            var position = this.options.position,
                pos_str = position[0].split('-'),
                pos = [0, 0];
            if (position.length > 1) {
                pos = position[1];
            }

            if (pos[0] > -1 && pos[0] < 1) {
                pos[0] = pos[0] * $(window).height();
            }
            if (pos[1] > -1 && pos[1] < 1) {
                pos[1] = pos[1] * $(window).width();
            }

            for (var i in pos_str) {
                if ($.type(pos_str[i]) !== 'string') {
                    continue;
                }
                var str = pos_str[i].toLowerCase();

                if ($.inArray(str, ['left', 'right']) > -1) {
                    alertDiv.css(str, pos[1]);
                } else if ($.inArray(str, ['top', 'bottom']) > -1) {
                    alertDiv.css(str, pos[0] + ie6);
                } else {
                    alertDiv.css({
                        'top': ($(window).height() - alertDiv.outerHeight()) / 2 + pos[0] + ie6,
                        'left': ($(window).width() - alertDiv.outerWidth()) / 2 + pos[1]
                    });
                }
            }

            if (parseInt(alertDiv.css('top')) < this.options.minTop) {
                alertDiv.css('top', this.options.minTop);
            }
        },

        bind_event: function () {
            this.bind_show();
            this.bind_close();

            if ($.browser && $.browser.msie && $.browser.version == '6.0') {
                this.bind_scroll();
            }
        },

        bind_show: function () {
            var ops = this.options;
            this.alertDiv.fadeIn(ops.speed, function () {
                ops.onShow($(this));
            });
        },

        bind_close: function () {
            var alertDiv = this.alertDiv,
                ops = this.options,
                closeBtn = $('.close', alertDiv).add($(this.options.close, alertDiv));

            closeBtn.bind('click', function (e) {
                alertDiv.fadeOut(ops.speed, function () {
                    $(this).remove();
                    ops.onClose($(this));
                });
                e.stopPropagation();
            });

            if (this.options.autoClose) {
                var time = parseInt(this.options.closeTime / 1000);
                if (this.options.withTime) {
                    $('p', alertDiv).append('<span>...<em>' + time + '</em></span>');
                }
                var timer = setInterval(function () {
                    $('em', alertDiv).text(--time);
                    if (!time) {
                        clearInterval(timer);
                        closeBtn.trigger('click');
                    }
                }, 1000);
            }
        },

        // IE6
        bind_scroll: function () {
            var alertDiv = this.alertDiv,
                top = alertDiv.offset().top - $(window).scrollTop();
            $(window).scroll(function () {
                alertDiv.css("top", top + $(window).scrollTop());
            })
        },

        check_mobile: function () {
            var userAgent = navigator.userAgent;
            var keywords = ['Android', 'iPhone', 'iPod', 'iPad', 'Windows Phone', 'MQQBrowser'];
            for (var i in keywords) {
                if (userAgent.indexOf(keywords[i]) > -1) {
                    return keywords[i];
                }
            }
            return false;
        }
    };

    $.alert = function (msg, arg) {
        if ($.alert_ext.check_mobile()) {
            alert(msg);
            return;
        }
        if (!$.trim(msg).length) {
            return false;
        }
        if ($.type(arg) === "string") {
            arg = {
                title: arg
            }
        }
        if (arg && arg.type == 'error') {
            arg.type = 'danger';
        }
        return $.alert_ext.init(msg, arg);
    }
})(jQuery);

No comments:

Post a Comment