Add Multiple Elements to Page - javascript

I have created a JQuery tooltip plugin and I am applying it to a few A tags.
For each A tag there should be a different tooltip associated with it so I have:
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
Where the tooltip id includes a random number created as follows:
id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000)
The plugin does not behave well. I checked the HTML added to the page.
Only one tooltip is being added to the page ... Always the same.
How can I fix this? What am I doing wrong?
I have an example in: http://codepen.io/mdmoura/pen/wgapv
And the plugin code is the following:
$(document).ready(function () {
$("table a").Tooltip();
});
// Tooltip
(function ($) {
$.fn.Tooltip = function (options) {
var defaults = {
class: 'Tooltip',
delay: [200, 200],
offset: [0, -10],
hide: function ($element, $tooltip) {
$tooltip.fadeOut(200);
},
show: function ($element, $tooltip) {
$tooltip.fadeIn(200);
}
};
var options = $.extend({}, defaults, options);
var tooltip = { id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000), ready: false, timer: null, title: '' };
$(this).each(function (e) {
var $this = $(this);
tooltip.title = $this.attr('title') || '';
$this.mouseenter(function (e) {
if (tooltip.ready) {
var $tooltip = $("#" + tooltip.id);
} else {
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
$tooltip.html(tooltip.title);
tooltip.ready = true;
$this.attr('title', '');
}
var position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
$tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });
tooltip.timer = window.setTimeout(function () {
options.show($this, $tooltip.stop(true, true));
}, options.delay[0] || 0);
$("#" + tooltip.id).mouseenter(function () {
window.clearTimeout(tooltip.timer);
tooltip.timer = null;
}); // Tooltip enter
$("#" + tooltip.id).mouseleave(function () {
tooltip.timer = setTimeout(function () {
options.hide($this, $tooltip);
}, 0);
});
}), // Mouse enter
$this.mouseleave(function (e) {
tooltip.timer = setTimeout(function () {
options.hide($this, $("#" + tooltip.id).stop(true, true));
}, options.delay[1] || 0);
}) // Mouse leave
}); // Each
}; // Tooltip
})(jQuery); // JQuery
And the HTMl is the following:
<table>
<tr><td>Tooltip 01</td></tr>
<tr><td>Tooltip 02</td></tr>
<tr><td>Tooltip 03</td></tr>
<tr><td>Tooltip 04</td></tr>
<tr><td>Tooltip 05</td></tr>
</table>
Thank you!

you have the var tooltip definded outside the this.each loop, which means there will be only one tooltip instance
(function ($) {
$.fn.Tooltip = function (options) {
var defaults = {
class: 'Tooltip',
delay: [200, 200],
offset: [0, -10],
hide: function ($element, $tooltip) {
$tooltip.fadeOut(200);
},
show: function ($element, $tooltip) {
$tooltip.fadeIn(200);
}
};
var options = $.extend({}, defaults, options);
$(this).each(function (e) {
//moved this inside the loop
var tooltip = { id: "Tooltip_" + Math.floor(Math.random() * (9999 - 2000 + 1) + 2000), ready: false, timer: null, title: '' };
var $this = $(this);
tooltip.title = $this.attr('title') || '';
$this.mouseenter(function (e) {
if (tooltip.ready) {
var $tooltip = $("#" + tooltip.id);
} else {
var $tooltip = $("<div>").attr("id", tooltip.id).attr("class", options.class).appendTo('body');
$tooltip.html(tooltip.title);
tooltip.ready = true;
$this.attr('title', '');
}
var position = [e.clientX + options.offset[0], e.clientY + options.offset[1]];
$tooltip.css({ left: position[0] + 'px', top: position[1] + 'px' });
tooltip.timer = window.setTimeout(function () {
options.show($this, $tooltip.stop(true, true));
}, options.delay[0] || 0);
$("#" + tooltip.id).mouseenter(function () {
window.clearTimeout(tooltip.timer);
tooltip.timer = null;
}); // Tooltip enter
$("#" + tooltip.id).mouseleave(function () {
tooltip.timer = setTimeout(function () {
options.hide($this, $tooltip);
}, 0);
});
}), // Mouse enter
$this.mouseleave(function (e) {
tooltip.timer = setTimeout(function () {
options.hide($this, $("#" + tooltip.id).stop(true, true));
}, options.delay[1] || 0);
}) // Mouse leave
}); // Each
}; // Tooltip
})(jQuery);
Demo: CodePen

Related

Too Many classes assigned to divs on click

I manage the design for this company, they had someone else write the code for these tabs and it keeps adding too many "active" classes on inactive tabs.
I have been trying to fix this for hours, but this seems overly complicated.
This is the result on the page and on the code. https://drive.google.com/drive/folders/1cxNscwXqKpeUvvuKwKsgdoAIiVNzYKwL?usp=sharing
Thank you for your help!
<script>
jQuery(document).ready(function() {
// ======================================================================
var IngredientsViewer = {
init: function() {
this.setupEventListeners();
this.adjustHeights();
},
// ====================================================================
switchProduct: function(e) {
var $target = jQuery(e.currentTarget);
var $navs = jQuery('.js-ingredients-product-nav');
var $lists = jQuery('.js-ingredients-product-content');
var id = $target.data('id');
var $list;
if ($target.hasClass('active')) { return; }
$navs.removeClass('active');
$target.addClass('active');
this.scrollToIngredients();
$lists.each(function(i, list) {
$list = jQuery(list);
if ($list.hasClass('active')) {
$list.removeClass('active');
(function($list) {
setTimeout(function() {
$list.addClass('mobile-hide');
}, 300);
})($list);
} else {
(function($list) {
setTimeout(function() {
$list.removeClass('mobile-hide');
}, 250);
})($list);
(function($list) {
setTimeout(function() {
$list.addClass('active');
}, 300);
})($list);
}
});
},
// ====================================================================
switchList: function(e) {
var $target = jQuery(e.currentTarget);
var $wrapper = $target.closest('.js-ingredients-product-content');
var $navs = $wrapper.find('.js-ingredients-nav-item');
var $lists = $wrapper.find('.js-ingredients-list');
var id = $target.data('id');
var $list;
if ($target.hasClass('active')) { return; }
$navs.removeClass('active');
$target.addClass('active');
$lists.each(function(i, list) {
$list = jQuery(list);
if ($list.hasClass('active')) {
$list.removeClass('active');
(function($list) {
setTimeout(function() {
$list.addClass('mobile-hide');
}, 300);
})($list);
} else {
(function($list) {
setTimeout(function() {
$list.removeClass('mobile-hide');
}, 250);
})($list);
(function($list) {
setTimeout(function() {
$list.addClass('active');
}, 300);
})($list);
}
});
},
// ====================================================================
switchDescription: function(e) {
var $target = jQuery(e.currentTarget);
var $description = jQuery('.js-ingredients-description');
var template = this.createDescriptionTemplate({
title: $target.data('title'),
details1: $target.data('details-1'),
details2: $target.data('details-2')
});
if (template) {
$description.removeClass('show');
this.openModal();
setTimeout(function() {
$description.html(template);
$description.addClass('show');
}, 300);
}
},
// ====================================================================
scrollToIngredients: function() {
var ingredients = jQuery('.js-product-content-wrapper')[0];
var offset;
if (ingredients && window.innerWidth <= 900) {
offset = this.getOffsetTop(ingredients) - 50;
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
setTimeout(function() {
window.scrollTo(0, offset);
}, 300);
} else {
jQuery('html').animate({ scrollTop: offset }, 300);
}
}
},
// ======================================================================
getOffsetTop: function(el) {
var top = 0;
while(el) {
top += el.offsetTop;
el = el.offsetParent;
}
return top;
},
// ====================================================================
createDescriptionTemplate: function(data) {
var template = '';
var subTemplate;
if (data.title && data.details1) {
template += '<h3>What is <span>' + data.title + '</span>?</h3>';
template += '<div>' + data.details1 + '</div>';
}
if (data.details2) {
template += '<h3>Why did we choose it?</h3>';
template += '<div>' + data.details2 + '</div>';
}
return template;
},
// ====================================================================
adjustHeights: function() {
this.adjustIngredientHeights();
},
// ====================================================================
adjustIngredientHeights: function() {
var $wrapper = jQuery('.js-ingredient-label');
var $inner = jQuery('.js-ingredient-label-inner');
var heights = $inner.map(function(i, p) { return p.offsetHeight; });
var max = Math.max.apply(Math, heights);
if ($inner.length && max) {
$wrapper.css({ 'minHeight': max + 'px' });
}
},
// ====================================================================
openModal: function() {
if (window.innerWidth <= 900) {
jQuery('.js-ingredients-modal').fadeIn(400);
}
},
// ====================================================================
closeModal: function(e) {
jQuery(e.currentTarget).fadeOut(400);
},
// ====================================================================
setupEventListeners: function() {
jQuery(document).on('click', '.js-ingredients-nav-item', this.switchList.bind(this));
jQuery(document).on('click', '.js-ingredients-list-item', this.switchDescription.bind(this));
jQuery(document).on('click', '.js-ingredients-modal', this.closeModal.bind(this));
jQuery(document).on('click', '.js-ingredients-product-nav', this.switchProduct.bind(this));
jQuery(window).on('resize', this.adjustHeights.bind(this));
}
};
// ======================================================================
Object.create(IngredientsViewer).init();
// ======================================================================
});
</script>

How can I make my JQuery run again when using goBack() in React

I have react app using Switch of react-router-dom. When people click they can see the profile of a person in full, but I want a goBack button, so I did this.
const onClick = () => {
return history.goBack();
}
The problem is, when I go back to the last page, the jQuery libraries I'm using don't work, and even some code I'm using in useEffect. I'm using forceRefresh in my Router so every time I go to another page in the Switch I can see the animations an load the actions, is not the best solution but has been working so far.
EDIT:
I'm adding the jQuery file, maybe this helps. This file is called in index.html of the public folder
<script src="%PUBLIC_URL%/assets/js/custom.js" async defer></script>
Code:
(function ($) {
'use strict';
$(document).ready(function () {
$(function () {
function mmenuInit() {
var wi = $(window).width();
if (wi <= '1099') {
$('.mmenu-init').remove();
$('#navigation')
.clone()
.addClass('mmenu-init')
.insertBefore('#navigation')
.removeAttr('id')
.removeClass('style-1 style-2')
.find('ul, div')
.removeClass(
'style-1 style-2 mega-menu mega-menu-content mega-menu-section'
)
.removeAttr('id');
$('.mmenu-init').find('ul').addClass('mm-listview');
$('.mmenu-init').find('.mobile-styles .mm-listview').unwrap();
$('.mmenu-init').mmenu(
{
counters: true,
},
{
// configuration
offCanvas: {
pageNodetype: '#wrapper',
},
}
);
var mmenuAPI = $('.mmenu-init').data('mmenu');
var $icon = $('.mmenu-trigger .hamburger');
$(document).on('click', '.mmenu-trigger', function () {
mmenuAPI.open();
});
}
$('.mm-next').addClass('mm-fullsubopen');
}
mmenuInit();
$(window).resize(function () {
mmenuInit();
});
});
$(window).on('load resize', function () {
var transparentHeaderHeight = $('.transparent-header').outerHeight();
$('.transparent-header-spacer').css({
height: transparentHeaderHeight,
});
});
$('.ripple-effect, .ripple-effect-dark').on('click', function (e) {
var rippleDiv = $('<span class="ripple-overlay">'),
rippleOffset = $(this).offset(),
rippleY = e.pageY - rippleOffset.top,
rippleX = e.pageX - rippleOffset.left;
rippleDiv
.css({
top: rippleY - rippleDiv.height() / 2,
left: rippleX - rippleDiv.width() / 2,
// background: $(this).data("ripple-color");
})
.appendTo($(this));
window.setTimeout(function () {
rippleDiv.remove();
}, 800);
});
$('.switch, .radio').each(function () {
var intElem = $(this);
intElem.on('click', function () {
intElem.addClass('interactive-effect');
setTimeout(function () {
intElem.removeClass('interactive-effect');
}, 400);
});
});
$(window).on('load', function () {
$('.button.button-sliding-icon')
.not('.task-listing .button.button-sliding-icon')
.each(function () {
var buttonWidth = $(this).outerWidth() + 30;
$(this).css('width', buttonWidth);
});
});
$('.bookmark-icon').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('.bookmark-button').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('a.close')
.removeAttr('href')
.on('click', function () {
function slideFade(elem) {
var fadeOut = { opacity: 0, transition: 'opacity 0.5s' };
elem.css(fadeOut).slideUp();
}
slideFade($(this).parent());
});
// Closing function
function close_user_dropdown() {
$('.header-notifications').removeClass('active');
}
// Closes notification dropdown on click outside the conatainer
var mouse_is_inside = false;
$('.header-notifications').on('mouseenter', function () {
mouse_is_inside = true;
});
$('.header-notifications').on('mouseleave', function () {
mouse_is_inside = false;
});
$('body').mouseup(function () {
if (!mouse_is_inside) close_user_dropdown();
});
// Close with ESC
$(document).keyup(function (e) {
if (e.keyCode == 27) {
close_user_dropdown();
}
});
if ($('.status-switch label.user-invisible').hasClass('current-status')) {
$('.status-indicator').addClass('right');
}
$('.status-switch label.user-invisible').on('click', function () {
$('.status-indicator').addClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-invisible').addClass('current-status');
});
$('.status-switch label.user-online').on('click', function () {
$('.status-indicator').removeClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-online').addClass('current-status');
});
// Wrapper Height (window height - header height)
function wrapperHeight() {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
$(
'.full-page-content-container, .dashboard-content-container, .dashboard-sidebar-inner, .dashboard-container, .full-page-container'
).css({ height: windowHeight });
$('.dashboard-content-inner').css({ 'min-height': windowHeight });
}
// Enabling Scrollbar
function fullPageScrollbar() {
$('.full-page-sidebar-inner, .dashboard-sidebar-inner').each(function () {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
var sidebarContainerHeight = $(this)
.find('.sidebar-container, .dashboard-nav-container')
.outerHeight();
// Enables scrollbar if sidebar is higher than wrapper
if (sidebarContainerHeight > windowHeight) {
$(this).css({ height: windowHeight });
} else {
$(this).find('.simplebar-track').hide();
}
});
}
// Init
$(window).on('load resize', function () {
wrapperHeight();
fullPageScrollbar();
});
wrapperHeight();
fullPageScrollbar();
// Sliding Sidebar
$('.enable-filters-button').on('click', function () {
$('.full-page-sidebar').toggleClass('enabled-sidebar');
$(this).toggleClass('active');
$('.filter-button-tooltip').removeClass('tooltip-visible');
});
/* Enable Filters Button Tooltip */
$(window).on('load', function () {
$('.filter-button-tooltip')
.css({
left: $('.enable-filters-button').outerWidth() + 48,
})
.addClass('tooltip-visible');
});
// Avatar Switcher
function avatarSwitcher() {
var readURL = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.profile-pic').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
};
$('.file-upload').on('change', function () {
readURL(this);
});
$('.upload-button').on('click', function () {
$('.file-upload').click();
});
}
avatarSwitcher();
// Dashboard Nav Submenus
$('.dashboard-nav ul li a').on('click', function (e) {
if ($(this).closest('li').children('ul').length) {
if ($(this).closest('li').is('.active-submenu')) {
$('.dashboard-nav ul li').removeClass('active-submenu');
} else {
$('.dashboard-nav ul li').removeClass('active-submenu');
$(this).parent('li').addClass('active-submenu');
}
e.preventDefault();
}
});
// Responsive Dashbaord Nav Trigger
$('.dashboard-responsive-nav-trigger').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('active');
var dashboardNavContainer = $('body').find('.dashboard-nav');
if ($(this).hasClass('active')) {
$(dashboardNavContainer).addClass('active');
} else {
$(dashboardNavContainer).removeClass('active');
}
$('.dashboard-responsive-nav-trigger .hamburger').toggleClass(
'is-active'
);
});
// Fun Facts
function funFacts() {
/*jslint bitwise: true */
function hexToRgbA(hex) {
var c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length == 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return (
'rgba(' +
[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') +
',0.07)'
);
}
}
$('.fun-fact').each(function () {
var factColor = $(this).attr('data-fun-fact-color');
if (factColor !== undefined) {
$(this)
.find('.fun-fact-icon')
.css('background-color', hexToRgbA(factColor));
$(this).find('i').css('color', factColor);
}
});
}
funFacts();
// Notes & Messages Scrollbar
$(window).on('load resize', function () {
var winwidth = $(window).width();
if (winwidth > 1199) {
// Notes
$('.row').each(function () {
var mbh = $(this).find('.main-box-in-row').outerHeight();
var cbh = $(this).find('.child-box-in-row').outerHeight();
if (mbh < cbh) {
var headerBoxHeight = $(this)
.find('.child-box-in-row .headline')
.outerHeight();
var mainBoxHeight =
$(this).find('.main-box-in-row').outerHeight() -
headerBoxHeight +
39;
$(this)
.find('.child-box-in-row .content')
.wrap(
'<div class="dashboard-box-scrollbar" style="max-height: ' +
mainBoxHeight +
'px" data-simplebar></div>'
);
}
});
// Messages Sidebar
// var messagesList = $(".messages-inbox").outerHeight();
// var messageWrap = $(".message-content").outerHeight();
// if ( messagesList > messagesWrap) {
// $(messagesList).css({
// 'max-height': messageWrap,
// });
// }
}
});
// Mobile Adjustment for Single Button Icon in Dashboard Box
$('.buttons-to-right').each(function () {
var btr = $(this).width();
if (btr < 36) {
$(this).addClass('single-right-button');
}
});
// Small Footer Adjustment
$(window).on('load resize', function () {
var smallFooterHeight = $('.small-footer').outerHeight();
$('.dashboard-footer-spacer').css({
'padding-top': smallFooterHeight + 45,
});
});
// Auto Resizing Message Input Field
/* global jQuery */
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el)
.css('height', 'auto')
.css('height', el.scrollHeight + offset);
};
jQuery(this)
.on('keyup input', function () {
resizeTextarea(this);
})
.removeAttr('data-autoresize');
});
function userMenuScrollbar() {
$('.header-notifications-scroll').each(function () {
var scrollContainerList = $(this).find('ul');
var itemsCount = scrollContainerList.children('li').length;
var notificationItems;
// Determines how many items are displayed based on items height
/* jshint shadow:true */
if (scrollContainerList.children('li').outerHeight() > 140) {
var notificationItems = 2;
} else {
var notificationItems = 3;
}
// Enables scrollbar if more than 2 items
if (itemsCount > notificationItems) {
var listHeight = 0;
$(scrollContainerList)
.find('li:lt(' + notificationItems + ')')
.each(function () {
listHeight += $(this).height();
});
$(this).css({ height: listHeight });
} else {
$(this).css({ height: 'auto' });
$(this).find('.simplebar-track').hide();
}
});
}
// Init
userMenuScrollbar();
/* global tippy */
tippy('[data-tippy-placement]', {
delay: 100,
arrow: true,
arrowType: 'sharp',
size: 'regular',
duration: 200,
// 'shift-toward', 'fade', 'scale', 'perspective'
animation: 'shift-away',
animateFill: true,
theme: 'dark',
// How far the tooltip is from its reference element in pixels
distance: 10,
});
var accordion = (function () {
var $accordion = $('.js-accordion');
var $accordion_header = $accordion.find('.js-accordion-header');
// default settings
var settings = {
// animation speed
speed: 400,
// close all other accordion items if true
oneOpen: false,
};
return {
// pass configurable object literal
init: function ($settings) {
$accordion_header.on('click', function () {
accordion.toggle($(this));
});
$.extend(settings, $settings);
// ensure only one accordion is active if oneOpen is true
if (settings.oneOpen && $('.js-accordion-item.active').length > 1) {
$('.js-accordion-item.active:not(:first)').removeClass('active');
}
// reveal the active accordion bodies
$('.js-accordion-item.active').find('> .js-accordion-body').show();
},
toggle: function ($this) {
if (
settings.oneOpen &&
$this[0] !=
$this
.closest('.js-accordion')
.find('> .js-accordion-item.active > .js-accordion-header')[0]
) {
$this
.closest('.js-accordion')
.find('> .js-accordion-item')
.removeClass('active')
.find('.js-accordion-body')
.slideUp();
}
// show/hide the clicked accordion item
$this.closest('.js-accordion-item').toggleClass('active');
$this.next().stop().slideToggle(settings.speed);
},
};
})();
$(document).ready(function () {
accordion.init({ speed: 300, oneOpen: true });
});
$(window).on('load resize', function () {
if ($('.tabs')[0]) {
$('.tabs').each(function () {
var thisTab = $(this);
// Intial Border Position
var activePos = thisTab.find('.tabs-header .active').position();
function changePos() {
// Update Position
activePos = thisTab.find('.tabs-header .active').position();
// Change Position & Width
thisTab
.find('.tab-hover')
.stop()
.css({
left: activePos.left,
width: thisTab.find('.tabs-header .active').width(),
});
}
changePos();
// Intial Tab Height
var tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Tab Height
function animateTabHeight() {
// Update Tab Height
tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Height
thisTab
.find('.tabs-content')
.stop()
.css({
height: tabHeight + 'px',
});
}
animateTabHeight();
// Change Tab
function changeTab() {
var getTabId = thisTab
.find('.tabs-header .active a')
.attr('data-tab-id');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
thisTab
.find('.tab[data-tab-id=' + getTabId + ']')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
}
// Tabs
thisTab.find('.tabs-header a').on('click', function (e) {
e.preventDefault();
// Tab Id
var tabId = $(this).attr('data-tab-id');
// Remove Active State
thisTab
.find('.tabs-header a')
.stop()
.parent()
.removeClass('active');
// Add Active State
$(this).stop().parent().addClass('active');
changePos();
// Update Current Itm
tabCurrentItem = tabItems.filter('.active');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
// Add Active State
thisTab
.find('.tab[data-tab-id="' + tabId + '"]')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
});
// Tab Items
var tabItems = thisTab.find('.tabs-header ul li');
// Tab Current Item
var tabCurrentItem = tabItems.filter('.active');
// Next Button
thisTab.find('.tab-next').on('click', function (e) {
e.preventDefault();
var nextItem = tabCurrentItem.next();
tabCurrentItem.removeClass('active');
if (nextItem.length) {
tabCurrentItem = nextItem.addClass('active');
} else {
tabCurrentItem = tabItems.first().addClass('active');
}
changePos();
changeTab();
});
// Prev Button
thisTab.find('.tab-prev').on('click', function (e) {
e.preventDefault();
var prevItem = tabCurrentItem.prev();
tabCurrentItem.removeClass('active');
if (prevItem.length) {
tabCurrentItem = prevItem.addClass('active');
} else {
tabCurrentItem = tabItems.last().addClass('active');
}
changePos();
changeTab();
});
});
}
});
// Thousand Separator
function ThousandSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// Bidding Slider Average Value
var avgValue =
(parseInt($('.bidding-slider').attr('data-slider-min')) +
parseInt($('.bidding-slider').attr('data-slider-max'))) /
2;
if ($('.bidding-slider').data('slider-value') === 'auto') {
$('.bidding-slider').attr({ 'data-slider-value': avgValue });
}
// Bidding Slider Init
$('.bidding-slider').slider();
$('.bidding-slider').on('slide', function (slideEvt) {
$('#biddingVal').text(ThousandSeparator(parseInt(slideEvt.value)));
});
$('#biddingVal').text(
ThousandSeparator(parseInt($('.bidding-slider').val()))
);
// Default Bootstrap Range Slider
var currencyAttr = $('.range-slider').attr('data-slider-currency');
$('.range-slider').slider({
formatter: function (value) {
return (
currencyAttr +
ThousandSeparator(parseInt(value[0])) +
' - ' +
currencyAttr +
ThousandSeparator(parseInt(value[1]))
);
},
});
$('.range-slider-single').slider();
var radios = document.querySelectorAll('.payment-tab-trigger > input');
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener('change', expandAccordion);
}
function expandAccordion(event) {
/* jshint validthis: true */
var tabber = this.closest('.payment');
var allTabs = tabber.querySelectorAll('.payment-tab');
for (var i = 0; i < allTabs.length; i++) {
allTabs[i].classList.remove('payment-tab-active');
}
event.target.parentNode.parentNode.classList.add('payment-tab-active');
}
$('.billing-cycle-radios').on('click', function () {
if ($('.billed-yearly-radio input').is(':checked')) {
$('.pricing-plans-container').addClass('billed-yearly');
}
if ($('.billed-monthly-radio input').is(':checked')) {
$('.pricing-plans-container').removeClass('billed-yearly');
}
});
function qtySum() {
var arr = document.getElementsByName('qtyInput');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
}
qtySum();
$('.qtyDec, .qtyInc').on('click', function () {
var $button = $(this);
var oldValue = $button.parent().find('input').val();
if ($button.hasClass('qtyInc')) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) + 1);
} else {
if (oldValue > 1) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) - 1);
} else {
$button.parent().find('input').val(1);
}
}
qtySum();
$('.qtyTotal').addClass('rotate-x');
});
/* global ClipboardJS */
$('.copy-url input').val(window.location.href);
new ClipboardJS('.copy-url-button');
$('.share-buttons-icons a').each(function () {
var buttonBG = $(this).attr('data-button-color');
if (buttonBG !== undefined) {
$(this).css('background-color', buttonBG);
}
});
var $tabsNav = $('.popup-tabs-nav'),
$tabsNavLis = $tabsNav.children('li');
$tabsNav.each(function () {
var $this = $(this);
$this
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.first()
.show();
$this.children('li').first().addClass('active').stop(true, true).show();
});
$tabsNavLis.on('click', function (e) {
var $this = $(this);
$this.siblings().removeClass('active').end().addClass('active');
$this
.parent()
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.siblings($this.find('a').attr('href'))
.fadeIn();
e.preventDefault();
});
var hash = window.location.hash;
var anchor = $('.tabs-nav a[href="' + hash + '"]');
if (anchor.length === 0) {
$('.popup-tabs-nav li:first').addClass('active').show(); //Activate first tab
$('.popup-tab-content:first').show(); //Show first tab content
} else {
anchor.parent('li').click();
}
// Link to Register Tab
$('.register-tab').on('click', function (event) {
event.preventDefault();
$('.popup-tab-content').hide();
$('#register.popup-tab-content').show();
$('body')
.find('.popup-tabs-nav a[href="#register"]')
.parent('li')
.click();
});
// Disable tabs if there's only one tab
$('.popup-tabs-nav').each(function () {
var listCount = $(this).find('li').length;
if (listCount < 2) {
$(this).css({
'pointer-events': 'none',
});
}
});
$('.indicator-bar').each(function () {
var indicatorLenght = $(this).attr('data-indicator-percentage');
$(this)
.find('span')
.css({
width: indicatorLenght + '%',
});
});
var uploadButton = {
$button: $('.uploadButton-input'),
$nameField: $('.uploadButton-file-name'),
};
uploadButton.$button.on('change', function () {
_populateFileField($(this));
});
function _populateFileField($button) {
var selectedFile = [];
for (var i = 0; i < $button.get(0).files.length; ++i) {
selectedFile.push($button.get(0).files[i].name + '<br>');
}
uploadButton.$nameField.html(selectedFile);
}
$('.default-slick-carousel').slick({
infinite: false,
slidesToShow: 3,
slidesToScroll: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1292,
settings: {
dots: true,
arrows: false,
},
},
{
breakpoint: 993,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
dots: true,
arrows: false,
},
},
{
breakpoint: 769,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: true,
arrows: false,
},
},
],
});
$('.testimonial-carousel').slick({
centerMode: true,
centerPadding: '30%',
slidesToShow: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1600,
settings: {
centerPadding: '21%',
slidesToShow: 1,
},
},
{
breakpoint: 993,
settings: {
centerPadding: '15%',
slidesToShow: 1,
},
},
{
breakpoint: 769,
settings: {
centerPadding: '5%',
dots: true,
arrows: false,
},
},
],
});
$('.logo-carousel').slick({
infinite: true,
slidesToShow: 5,
slidesToScroll: 1,
dots: false,
arrows: true,
responsive: [
{
breakpoint: 1365,
settings: {
slidesToShow: 5,
dots: true,
arrows: false,
},
},
{
breakpoint: 992,
settings: {
slidesToShow: 3,
dots: true,
arrows: false,
},
},
{
breakpoint: 768,
settings: {
slidesToShow: 1,
dots: true,
arrows: false,
},
},
],
});
$('.mfp-gallery-container').each(function () {
// the containers for all your galleries
$(this).magnificPopup({
type: 'image',
delegate: 'a.mfp-gallery',
fixedContentPos: true,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: false,
preloader: true,
removalDelay: 0,
mainClass: 'mfp-fade',
gallery: { enabled: true, tCounter: '' },
});
});
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in',
});
$('.mfp-image').magnificPopup({
type: 'image',
closeOnContentClick: true,
mainClass: 'mfp-fade',
image: {
verticalFit: true,
},
});
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false,
});
});
})(this.jQuery);
Thanks for any help.

Default filtering item

I have a page like this page:
http://www.sungeetheme.com/html/our_gallery_3_colums.html
In the filtering Gallery, the default item is "all"
How do I change the default to something else on page load, for example: Portrait?
I tried to change in the code section the variable dataFilterVal from "All" to something else and it did not work well
var masonryFilter = {
massMasonry: [],
dataFilterVal: "all",
init: function () {
var self = this;
self.filterEl('.j-filter', '~ .j-filter-content');
self.masonry();
},
masonry: function () {
var self = this;
var msnry;
var i = 0;
$('.j-masonry').each(function () {
var el = $(this),
newClass = 'j-masonry-' + i;
el.addClass(newClass).attr('data-masonry-id', i);
i++;
el.imagesLoaded(function () {
var container = document.querySelector('.' + newClass);
msnry = new Masonry(container,
{
itemSelector: '.j-masonry-item',
columnWidth: '.' + newClass + ' .masonry-gridSizer',
transitionDuration: '1.2s'
});
self.massMasonry.push(msnry);
el.data('masonry', msnry);
});
});
},
filterEl: function (filterNav, filterContent) {
var self = this;
$(filterNav + ' a').click(function (e) {
e.preventDefault();
var el = $(this);
var activeClass = "is-category-filter-active";
var activeContainer = $(filterContent, $(this).parents(filterNav)).eq(0);
console.log(activeContainer);
$('li', $(this).parents(filterNav)).removeClass(activeClass);
el.closest('li').addClass(activeClass);
self.dataFilterVal = el.attr('data-filter');
self.filterStart(self.dataFilterVal, activeContainer);
});
},
filterStart: function (dataFilterVal, filterContent) {
var self = this;
if (dataFilterVal == "all") {
$('[class*="j-filter-"]', filterContent).show().stop(true, false).animate({
opacity: 1
}, 400);
} else {
var hideItems = $('[class*="j-filter-"]', filterContent).not(dataFilterVal);
hideItems.stop(true, false).animate({
opacity: 0
}, 400);
setTimeout(function () {
hideItems.hide();
}, 301);
$(dataFilterVal, filterContent).show().stop(true, false).animate({
opacity: 1
}, 400);
}
setTimeout(function () {
var masonryId = $(filterContent).find('.j-masonry').attr('data-masonry-id');
self.massMasonry[masonryId].layout();
}, 501);
}
};
masonryFilter.init();

Ajax Call with tab open

I have the following problem with jquery:
$(function() {
var linkCorretto = $("#id").text();
var authWindow;
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#' + modalLocation).reveal($(this).data());
});
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop',
animationspeed: 300,
closeonbackgroundclick: false,
dismissmodalclass: 'close'
};
var options = $.extend({}, defaults, options);
var altezza = $(window).height();
altezza = altezza * 0.5;
return this.each(function() {
var modal = $(this),
modalheight = modal.height() * 0.8;
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if (modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
modal.bind('reveal:open', function() {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if (!locked) {
lockModal();
//modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(window).scrollTop()+topMeasure});
modal.css({
'opacity': 0,
'visibility': 'visible',
'top': $(window).scrollTop() + altezza - modalheight
});
$('body').css('overflow-y', 'hidden')
modalBG.fadeIn(options.animationspeed / 2);
modal.delay(options.animationspeed / 2).animate({
"opacity": 1
}, options.animationspeed, unlockModal());
}
modal.unbind('reveal:open');
$('.warning').hide();
$('.loading').hide();
$('.loadingoff').show();
$('.reveal-modal').addClass('background');
});
modal.bind('reveal:close', function() {
if (!locked) {
lockModal();
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity": 0
}, options.animationspeed, function() {
modal.css({
'opacity': 1,
'visibility': 'hidden',
'top': topMeasure
});
$('body').css('overflow-y', 'auto')
unlockModal();
});
}
modal.unbind('reveal:close');
});
modal.trigger('reveal:open')
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function() {
modal.trigger('reveal:close')
});
/*
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); }
});
*/
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});
}
// $.fn.reveal
$(".accetta").click(function() {
var dati = new Object();
dati = $("#listaCarte").val();
var imageUrl = '';
var x = ($('.reveal-modal').height());
$('.loadingoff').hide();
$('.loading').css('height', x).show();
$('.reveal-modal').removeClass('background');
$('<input>').attr({
type: 'hidden',
id: 'linkDaSostituire',
name: 'linkDaSostituire',
value: linkCorretto,
});
setTimeout(function() {
$.ajax({
type: "POST",
url: "/portalppay/ScontiServlet",
data: {
"linkDaSostituire": linkCorretto,
"cartaSelezionata": dati
},
dataType: "html",
success: function(msg) {
//window.location = msg;
authWindow = window.open('about:blank');
authWindow.location.replace(msg);
//window.open(msg);
//var win=window.location(msg, '_blank');
//win.focus();
$('.reveal-modal').trigger('reveal:close');
},
error: function() {
$('.loadingoff').hide();
$('.loading').hide();
$('.warning').css('height', x - 40).show();
}
});
}, 400);
});
// .accetta
});
when I trigger the ajax call, with this block of code:
url: "/portalppay/ScontiServlet",
I get a url for an answer and I do see in the browser with the following code:
authWindow = window.open('about:blank');
authWindow.location.replace(msg);
the problem is that I can not render the link in a new tab, but always in a new pop-up!
someone can help me solve the problem?
Have you checked your browser settings?
It's the browser which choose how to open new windows.
In Firefox there is the Open new windows in a new tab instead option which tells the browser if it has to open new windows in a new tab or in a... new window.
Do note that this works only if you are calling window.open without the strWindowFeatures parameter, specifying it forces the browser (well, at least Firefox and Explorer, Chrome does not seem to have a similar option) to open the link in a new window.
For more informations: https://developer.mozilla.org/en-US/docs/Web/API/window.open

run stack plugin on mouse hover on the div

I am using the following plugin
http://playground.mobily.pl/jquery/mobily-notes/demo.html
which gives a very good stack, but the problem is when I use it for my gallery. All of the albums are auto rotating which looks odd. Is there any possible way to at least run the plugin after we hover on the div instead of auto run? The main code to run this is
$(function(){
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false,
positionMultiplier: 5
});
});
Notice: I am not the author but it's an MIT licensed plugin so there shouldn't be any problem with modifying and redistributing it here.
In spite of eye candy of the plugin, it's not elastic enough to extend.
You can use my modified version instead.
mobilynotes.js:
(function ($) {
$.fn.mobilynotes = function (options) {
var defaults = {
init: "rotate",
positionMultiplier: 5,
title: null,
showList: true,
autoplay: true,
interval: 4000,
hover: true,
index: 1
};
var sets = $.extend({}, defaults, options);
return this.each(function () {
var $t = $(this),
note = $t.find(".note"),
size = note.length,
autoplay;
var notes = {
init: function () {
notes.css();
if (sets.showList) {
notes.list()
}
if (sets.autoplay) {
notes.autoplay()
}
if (sets.hover) {
notes.hover()
}
notes.show()
},
random: function (l, u) {
return Math.floor((Math.random() * (u - l + 1)) + l)
},
css: function () {
var zindex = note.length;
note.each(function (i) {
var $t = $(this);
switch (sets.init) {
case "plain":
var x = notes.random(-(sets.positionMultiplier), sets.positionMultiplier),
y = notes.random(-(sets.positionMultiplier), sets.positionMultiplier);
$t.css({
top: y + "px",
left: x + "px",
zIndex: zindex--
});
break;
case "rotate":
var rotate = notes.random(-(sets.positionMultiplier), sets.positionMultiplier),
degrees = "rotate(" + rotate + "deg)";
$t.css({
"-webkit-transform": degrees,
"-moz-transform": degrees,
"-o-transform": degrees,
filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + rotate + ")",
zIndex: zindex--
})
}
$t.attr("note", i)
})
},
zindex: function () {
var arr = new Array();
note.each(function (i) {
arr[i] = $(this).css("z-index")
});
var z = Math.max.apply(Math, arr);
return z
},
list: function () {
$t.after($("<ul />").addClass("listNotes"));
var ul = $t.find(".listNotes"),
title = new Array();
if (sets.title != null) {
note.each(function (i) {
title[i] = $(this).find(sets.title).text()
})
} else {
title[0] = "Bad selector!"
}
for (x in title) {
$t.next(".listNotes").append($("<li />").append($("<a />").attr({
href: "#",
rel: x
}).text(title[x])))
}
},
autoplay: function () {
var i = 1,
autoplay = setInterval(function () {
i == size ? i = 0 : "";
var div = note.eq(i),
w = div.width(),
left = div.css("left");
notes.animate(div, w, left);
i++
}, sets.interval)
},
hover: function () {
$t.hover(function() {
var div = note.eq(sets.index),
w = div.width(),
left = div.css("left");
sets.index == size ? sets.index = 1 : sets.index += 1;
notes.animate(div, w, left);
},
function() {}
);
},
show: function () {
$t.next(".listNotes").find("a").click(function () {
var $t = $(this),
nr = $t.attr("rel"),
div = note.filter(function () {
return $(this).attr("note") == nr
}),
left = div.css("left"),
w = div.width(),
h = div.height();
clearInterval(autoplay);
notes.animate(div, w, left);
return false
})
},
animate: function (selector, width, position) {
var z = notes.zindex();
selector.animate({
left: width + "px"
}, function () {
selector.css({
zIndex: z + 1
}).animate({
left: position
})
})
}
};
notes.init()
})
}
}(jQuery));
Using new features:
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false,
autoplay: false,
index: 1, //starting index (new)
hover: true // (new)
});
Taking over where #username left off (excellent work), I have branched username's fiddle with the following changes to the config options:
Modified (from #username's code):
hover: (boolean) on hover, reverses the effect of autoplay
New:
click: (boolean) on click, advances to next note, then resumes autoplay, if active, in the hover state.
Internally, new next, stop and restart functions and modified init, autoplay and animate functions handle (combinations of) the options.
The trickiest part was to provide for a callback in animate to cause autoplay to resume after next (the click action) has completed. This has ramifications in several other functions. (On reflection there's undoubtedly a better way using deferreds - I will have a think about that)
Here's the fiddle (or this full page version), with settings that reflect #Sakshi Sharma original question. I set click to true but it could equally be set to false, depending on preference.
And here's the code:
(function($) {
$.fn.mobilynotes = function(options) {
var defaults = {
init: "rotate",
positionMultiplier: 5,
title: null,
showList: true,
autoplay: false,
hover: true,//when true, hovering reverses autoplay; when false, has no effect.
click: true,
interval: 4000,
index: 1
};
var settings = $.extend({}, defaults, options);
return this.each(function() {
var $t = $(this),
note = $t.find(".note"),
size = note.length,
autoplay,
currentIndex = 1;
var notes = {
init: function() {
notes.css();
if (settings.showList) {
notes.list();
}
if (settings.hover) {
var fn1 = settings.autoplay ? notes.stop : notes.restart;
var fn2 = settings.autoplay ? notes.restart : notes.stop;
$t.hover(fn1, fn2);
}
if (settings.click) {
clearInterval(autoplay);
//autoplay 0, hover 0: null
//autoplay 0, hover 1: autoplay
//autoplay 1, hover 0: autoplay
//autoplay 1, hover 1: null
var callback = ( (settings.autoplay && !settings.hover) || (!settings.autoplay && settings.hover) ) ? notes.autoplay : null;
$t.click(function(){
notes.next(callback);
});
}
if (settings.autoplay) {
notes.autoplay();
}
notes.show();
},
random: function(l, u) {
return Math.floor((Math.random() * (u - l + 1)) + l);
},
css: function() {
var zindex = note.length;
note.each(function(i) {
var $t = $(this);
switch (settings.init) {
case "plain":
var x = notes.random(-(settings.positionMultiplier), settings.positionMultiplier),
y = notes.random(-(settings.positionMultiplier), settings.positionMultiplier);
$t.css({
top: y + "px",
left: x + "px",
zIndex: zindex--
});
break;
case "rotate":
var rotate = notes.random(-(settings.positionMultiplier), settings.positionMultiplier),
degrees = "rotate(" + rotate + "deg)";
$t.css({
"-webkit-transform": degrees,
"-moz-transform": degrees,
"-o-transform": degrees,
filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + rotate + ")",
zIndex: zindex--
})
}
$t.attr("note", i)
});
},
zindex: function() {
var arr = new Array();
note.each(function(i) {
arr[i] = $(this).css("z-index")
});
var z = Math.max.apply(Math, arr);
return z
},
list: function() {
$t.after($("<ul />").addClass("listNotes"));
var ul = $t.find(".listNotes"),
title = new Array();
if (settings.title != null) {
note.each(function(i) {
title[i] = $(this).find(settings.title).text()
})
} else {
title[0] = "Bad selector!"
}
for (x in title) {
$t.next(".listNotes").append($("<li />").append($("<a />").attr({
href: "#",
rel: x
}).text(title[x])))
}
},
next: function(callback) {
callback = (!callback || typeof callback !== 'function') ? null : callback;
currentIndex = currentIndex % size;
notes.animate(note.eq(currentIndex), callback);
currentIndex++;
},
autoplay: function() {
notes.stop();
autoplay = setInterval(notes.next, settings.interval);
},
stop: function() {
clearInterval(autoplay);
},
restart: function() {
notes.next(notes.autoplay);
},
show: function() {
$t.next(".listNotes").find("a").click(function() {
var $t = $(this),
nr = $t.attr("rel"),
div = note.filter(function() {
return $(this).attr("note") == nr;
});
clearInterval(autoplay);
notes.animate(div);
return false;
})
},
animate: function(selector, callback) {
var width = selector.width(),
position = selector.css("left"),
z = notes.zindex();
selector.animate({
left: width + "px"
}, function() {
selector.css({
zIndex: z + 1
}).animate({
left: position
}, function(){
if(callback) {
callback();
}
});
});
}
};
notes.init()
})
}
}(jQuery));
Hiya there so demo here :) and hope this helps: http://jsfiddle.net/haf6J/14/show/ && http://jsfiddle.net/haf6J/14/ OR http://jsfiddle.net/haf6J/3/show/ && http://jsfiddle.net/haf6J/3/
Now the rotation will start when you hover the images and if you want further that one mouse out it should stop you can take a look into event .mouseout and you can stop the rotation i.e. remove the effect.
Like epascarello mentioned documentation is here http://playground.mobily.pl/jquery/mobily-notes.html
Please let me know and dont forget to accept if this helps (and upvote :)) cheers
Jquery Code
$('.notes_img').hover(function() {
$('.notes_img').mobilynotes({
init: 'rotate',
showList: false
});
});​

Categories

Resources