Jquery commonly used code and snippets

Click event on both static and dynamically created elements

$(document).off("click",'.invest-models').on('click', '.invest-models', function (e) {
	$(this).toggleClass('red-bg');
	if($(this).hasClass('red-bg')){
		$(this).html('Hide Models');
	}else{
		$(this).html('Display Models');
	}
});


How to close BS modal clicking outside modal

$("body").on("click", ".modal-dialog", function(e) {
    if ($(e.target).hasClass('modal-dialog')) {
        var hidePopup = $(this).parent().parent().attr('id');
        $('#' + hidePopup).modal('hide');
    }
});

 

Putting multiple ajax with closest parent element opacity from group of child button click

$('.add-to-cart,.favorite-add-to-cart').on('click', function() {
    var formdata =
        'data[Product][product_id]=' + $(this).data('product-id') +
        '&data[Product][category_id]=' + $(this).data('category-id') +
        '&data[Product][qty]=1' +
        '&data[Product][dba_id]=' + $(this).data('dba-id') +
        '&data[Product][shipping]=' + $(this).data('shipping');
    var productEle = $(this).closest('.col-md-3,.col-md-4,.item,.favorite-item');
    var pId = $(this).data('product-id');
    productEle.css("opacity", "0.5");
    $.ajax({
        type: "POST",
        url: "/market_place/carts/addToBasket",
        data: formdata,
        success: function(theResponse) {
            $.post("/market_place/carts/update_top_cart", {}, function(result) {
                $("#top_summary").html(result);
                App.initScrollBar();
                $.post("/market_place/carts/getProductBasket/" + pId, {}, function(response) {
                    $('#add-to-cart .modal-content').html(response);
                    $('#add-to-cart').modal({
                        'backdrop': false
                    });
                    productEle.css("opacity", "1.0");
                });
            });
        }
    });
});

In order to append styles on an existing styles jquery

 var style = $('#main').attr('style'); // firstly getting styles
 style+= 'background-color: '+bgColor+' !important;'; // secondly, appending styles
 $('#main').attr('style', style); // finally, resetting styles to an element