Default filtering item - javascript

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();

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>

Odoo 13 : Error Js "Could not find client action"

I received the following error: Could not find client action eacta_previsionnel_hebdomadaire
XML code
<record id="eacta_previsionnel_report_action_client" model="ir.actions.client" >
<field name="name">Prévisionnel hebdomadaire</field>
<field name="tag">eacta_previsionnel_hebdomadaire</field>
</record>
JS code :
odoo.define('eacta_previsionnel.eacta_previsionnel_hebdomadaire', function (require) {
'use strict';
var core = require('web.core');
var Widget = require('web.Widget');
var ControlPanelMixin = require('web.ControlPanelMixin');
var AbstractAction = require('web.AbstractAction');
var SearchView = require('web.SearchView');
var data = require('web.data');
var pyeval = require('web.pyeval');
var field_utils = require('web.field_utils');
var session = require('web.session');
var datepicker = require('web.datepicker');
var QWeb = core.qweb;
var _t = core._t;
var ClientAction = AbstractAction.extend(ControlPanelMixin, {
custom_events: {
search: '_onSearch',
},
events:{
'change .o_eacta_date_start': 'on_change_date_start',
'change .o_mps_save_input_text': 'save_line_prevision',
'click .o_eacta_product_name': 'open_eacta_product',
'click .o_eacta_variete_name': 'open_eacta_plantation',
'click .o_eacta_next_week': 'on_click_next_week',
'click .o_eacta_prev_week': 'on_click_prev_week',
},
init: function(parent, action) {
this.actionManager = parent;
this.action = action;
this.domain = [];
return this._super.apply(this, arguments);
},
render_search_view: function(){
var self = this;
var defs = [];
this._rpc({
model: 'ir.model.data',
method: 'get_object_reference',
args: ['eacta_mrp_base', 'eacta_search_mrp_farm_plantation'],
})
.then(function(view_id){
self.dataset = new data.DataSetSearch(this, 'eacta.r.variete.serre.period');
self.loadFieldView(self.dataset, view_id[1], 'search')
.then(function (fields_view) {
self.fields_view = fields_view;
var options = {
$buttons: $("<div>"),
action: this.action,
disable_groupby: true,
};
self.searchview = new SearchView(self, self.dataset, self.fields_view, options);
self.searchview.appendTo($("<div>")).then(function () {
self.$searchview_buttons = self.searchview.$buttons.contents();
self.update_cp();
defs.push(self.update_cp());
});
});
});
},
willStart: function() {
return this.get_html();
},
start: function() {
var self = this;
this.render_search_view();
return this._super.apply(this, arguments).then(function () {
self.$el.html(self.html);
});
},
re_renderElement: function() {
this.$el.html(this.html);
this.update_cp();
},
open_eacta_product: function(e){
this.do_action({
type: 'ir.actions.act_window',
res_model: "eacta.conf.culture",
res_id: parseInt($(e.target).data('product')),
views: [[false, 'form']],
});
},
open_eacta_plantation: function(e){
this.do_action({
type: 'ir.actions.act_window',
res_model: "eacta.r.variete.serre.period",
res_id: parseInt($(e.target).data('plantation')),
views: [[false, 'form']],
});
},
save_line_prevision: function(e){
var self = this;
var $input = $(e.target);
var target_value;
try {
target_value = field_utils.parse.float($input.val().replace(String.fromCharCode(8209), '-'));
} catch(err) {
return this.do_warn(_t("Wrong value entered!"), err);
}
return this._rpc({
model: 'eacta.data.recolte.previsionnel',
method: 'save_line_prevision',
args: [field_utils.parse.float($input.val()), parseInt($input.data('plantation')),$input.data('date')],
})
.done(function(res){
self.get_html().then(function() {
self.re_renderElement();
self.update_cp();
});
});
},
on_change_date_start: function(e){
var self = this;
var $input = $(".o_eacta_date_start").val();
var target_value;
try {
if ($input == ''){
this.do_warn(_t("Wrong value entered!"), "<ul><li>Date de debut</li></ul>");
return;
}
// target_value = field_utils.format.date(field_utils.parse.date($input, {}, {isUTC: true}));
} catch(err) {
return this.do_warn(_t("Wrong value entered!"), err);
}
return this._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'search',
args: [[]],
})
.then(function(res){
return self._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'write',
args: [res, {'date_start': $input}],
})
.done(function(result){
self.get_html().then(function() {
self.re_renderElement();
self.update_cp();
});
});
});
},
on_click_next_week: function(e){
var self = this;
var date = self.operation_date("next",7);
var max_next_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_max = new Date($('.o_eacta_date_start').getAttributes()["date-max"]);
if (max_next_date > date_max)
$(".o_eacta_date_start").val(field_utils.parse.date(date_max).format('DD/MM/YYYY'));
else
$(".o_eacta_date_start").val(date[0] + "/" + date[1] + "/" + date[2]);
self.on_change_date_start();
},
on_click_prev_week: function(e){
var self = this;
var date = self.operation_date("prev",7);
var min_prev_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_min = new Date($('.o_eacta_date_start').getAttributes()["date-min"]);
if (min_prev_date < date_min)
$(".o_eacta_date_start").val(field_utils.parse.date(date_min).format('DD/MM/YYYY'));
else
$(".o_eacta_date_start").val(date[0] + "/" + date[1] + "/" + date[2]);
self.on_change_date_start();
},
operation_date: function(operation,nbr_day){
var counter = 0;
counter = counter + nbr_day;
var today = new Date($(".o_eacta_date_start").datepicker( "getDate" ));
if (operation == "next")
today.setDate(today.getDate() + counter);
else if (operation == "prev")
today.setDate(today.getDate() - counter);
var formattedDate = new Date(today);
var d = ("0" + formattedDate.getDate()).slice(-2);
var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
var y = formattedDate.getFullYear();
return [d,m,y]
},
get_html: function() {
var self = this;
return this._rpc({
model: 'eacta.previsionnel.hebdomadaire',
method: 'get_html',
args: [this.domain],
})
.then(function (result) {
self.html = result.html;
self.report_context = result.report_context;
});
},
update_cp: function() {
var self = this;
self.readonly_input_previsionnel();
self.enabled_input_previsionnel();
self.sous_total_previsionnel();
self.total_previsionnel();
self.total_sous_total_previsionnel();
self.visibility_icon_next();
self.visibility_icon_prev();
this.update_control_panel({
breadcrumbs: this.actionManager.get_breadcrumbs(),
cp_content: {
$buttons: this.$buttons,
$searchview: this.searchview.$el,
// $searchview_buttons: this.$searchview_buttons,
$searchview_buttons: this.$searchview_buttons
},
searchview: this.searchview,
});
},
total_previsionnel: function() {
$('.demand_forecast').each(function () {
var sum = 0.00
$(this).find('.text-right .o_mps_save_input_text').each(function () {
sum += Number(field_utils.parse.float($(this).context.value));
});
$(this).find('.o_mps_save_input_text_total').html(field_utils.format.float(sum));
});
},
sous_total_previsionnel: function(){
var list_periode = [];
var sum = 0.00;
$('tr.demand_forecast:first td.text-right input').each(function () {
list_periode.push($(this)[0].attributes['data-date'].value);
});
for (var i = 0;i< list_periode.length;i++){
$('.demand_forecast') .parent() .each(function () {
sum = 0.00;
$(this).find('input[data-date='+list_periode[i]+']').each(function () {
sum += field_utils.parse.float($(this).context.value);
});
$(this).parent().find('span[class=o_eacta_sous_total][data-date='+list_periode[i]+']').html(field_utils.format.float(sum));
});
}
},
total_sous_total_previsionnel: function(){
var sum = 0.00;
$('.demand_forecast').parent().parent().each(function () {
$(this).find('span[class=o_eacta_sous_total]').each(function () {
sum += field_utils.parse.float($(this).text());
});
$(this).find('tr.active td:last .o_eacta_total_sous_total').html(field_utils.format.float(sum));
sum = 0.00;
});
},
enabled_input_previsionnel: function() {
$('.demand_forecast').each(function () {
$(this).find('.eacta_readonly').each(function () {
$(this).prop('disabled', true);
$(this).prop('readonly', true);
$(this).css('background-color', 'transparent');
$(this).css('color', '#AEA79F');
});
});
},
readonly_input_previsionnel: function() {
$('.demand_forecast').each(function () {
$(this).find('.eacta_input_span_readonly').each(function () {
$(this).prop('disabled', true);
$(this).prop('readonly', true);
$(this).css('background-color', '#ffffff');
$(this).css('border', 'medium none');
});
});
},
visibility_icon_next:function(){
var self = this;
var date = self.operation_date("next",7);
var max_next_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_max = new Date($('.o_eacta_date_start').getAttributes()["date-max"]);
if (max_next_date > date_max)
$('.o_eacta_next_week').css('visibility', 'hidden');
else
$('.o_eacta_next_week').css('visibility', 'visible');
},
visibility_icon_prev:function(){
var self = this;
var date = self.operation_date("prev",7);
var min_prev_date = new Date(date[2], parseInt(date[1])-1,date[0])
var date_min = new Date($('.o_eacta_date_start').getAttributes()["date-min"]);
if (min_prev_date < date_min)
$('.o_eacta_prev_week').css('visibility', 'hidden');
else
$('.o_eacta_prev_week').css('visibility', 'visible');
},
_onSearch: function (event) {
var session = this.getSession();
var result = pyeval.eval_domains_and_contexts({
contexts: [session.user_context],
domains: event.data.domains
});
this.domain = result.domain;
this.update_cp();
this.get_html().then(this.re_renderElement.bind(this));
},
});
core.action_registry.add('eacta_previsionnel_hebdomadaire', ClientAction );
return ClientAction ;
});
I am using Odoo 13
What I am doing wrong here?
Let me know if you need more details.
thanks!

prevent slideshow from refresh or load content in div

I have a nice working image slideshow, but every time when i open a new page from the menu, the slideshow starts from the beginning. I want it to go on where it was while entering a new page. Now could there be a possibility to change it in the code of my slideshow, but maybe a better solution is to open my content in a div with AJAX, so the whole page doesn't refresh.
I found this on the web:
<div id="navigatie">
<div id="buttons">
<a class="menu" id="page1" href="#">Home</a><span>|</span>
<a class="menu" id="page2" href="#">Projects</a><span>|</span>
<a class="menu" id="page3" href="#">About</a><span>|</span>
</div>
</div>
<script>
$(document).ready(function() {
$("#page1").click(function(){
$('#content').load('index.php #content');
});
$("#page2").click(function(){
$('#content').load('projects.php #content');
});
$("#page3").click(function(){
$('#content').load('about.php #content');
});
});
</script>
But this doesn't workout very well because when i start with my index page and go to projects (where lightbox is present), i get full images instead of thumbnails.(This was because the extended files were not in #content) i get index.php# instead of projects.php. Maybe i should use an easier solution, but im getting stuck. Can someone help me out please?
Edit: Let me also share the code of the slideshow with you, perhaps there is a possibility to resume after loading a new page/refresh.
/*!
* crosscover v1.0.2
* Carousel of a simple background image using jquery and animate.css.
* http://git.blivesta.com/crosscover
* License : MIT
* Author : blivesta <enmt#blivesta.com> (http://blivesta.com/)
*/
;(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
'use strict';
var namespace = 'crosscover';
var __ = {
init: function(options) {
options = $.extend({
inClass: 'fade-in',
outClass: 'fade-out',
interval: 5000,
startIndex: 0,
autoPlay: true,
dotsNav: true,
controller: false,
controllerClass: 'crosscover-controller',
prevClass: 'crosscover-prev',
nextClass: 'crosscover-next',
playerClass: 'crosscover-player',
playerInnerHtml: '<span class="crosscover-icon-player"></span>',
prevInnerHtml: '<span class="crosscover-icon-prev"></span>',
nextInnerHtml: '<span class="crosscover-icon-next"></span>'
}, options);
__.settings = {
currentIndex: options.startIndex,
timer: null,
coverBaseClass:'crosscover-item',
coverWaitClass:'is-wait',
coverActiveClass:'is-active',
playerActiveClass: 'is-playing',
dotsNavClass: 'crosscover-dots'
};
return this.each(function() {
var _this = this;
var $this = $(this);
var data = $this.data(namespace);
var $item = $this.children('.crosscover-list').children('.' + __.settings.coverBaseClass);
if (!data) {
options = $.extend({}, options);
$this.data(namespace, {
options: options
});
if (options.dotsNav) __.createDots.call(_this, $item);
if (options.controller) __.createControler.call(_this, $item);
__.setup.call(_this, $item);
}
});
},
setup: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
$item.each(function(index) {
var $self = $(this);
var image = $self.find('img').attr('src');
$self
.addClass(__.settings.coverBaseClass, __.settings.coverWaitClass)
.css({
'background-image': 'url(' + image + ')'
});
});
return __.slideStart.call(_this, $item);
},
slideStart: function($item) {
var _this = this;
__.autoPlayStart.call(_this, $item);
__.show.call(_this, $item);
},
createDots: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var len = $item.length;
$this
.append(
$('<ul>')
.addClass(__.settings.dotsNavClass)
);
for (var i = 0; i < len; i++) {
$this
.children('.' + __.settings.dotsNavClass)
.append(
$('<li>')
.addClass('crosscover-dots-nav-' + i)
.append(
$('<button>')
)
);
}
__.addDots.call(_this, $item);
},
addDots: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $dots = $this.children('.' + __.settings.dotsNavClass);
var $dot = $dots.children('li').children('button');
$dot.on('click.' + namespace, function(event) {
return __.toggle.call(_this, $item, 'dots', $(this).parent('li').index());
});
},
createControler: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var isClass = options.autoPlay ? __.settings.playerActiveClass : null;
$this
.append(
$('<div>')
.attr({
'data-crosscover-controller': ''
})
.addClass(options.controllerClass)
.append(
$('<button>')
.attr({
'data-crosscover-prev': ''
})
.addClass(options.prevClass)
.html(options.prevInnerHtml)
)
.append(
$('<button>')
.attr({
'data-crosscover-player': ''
})
.addClass(options.playerClass)
.addClass(isClass)
.html(options.playerInnerHtml)
)
.append(
$('<button>')
.attr({
'data-crosscover-next': ''
})
.addClass(options.nextClass)
.html(options.nextInnerHtml)
)
);
return __.addControler.call(_this, $item);
},
addControler: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $controller = $this.children('[data-crosscover-controller]');
var $navPrev = $controller.children('[data-crosscover-prev]');
var $navNext = $controller.children('[data-crosscover-next]');
var $navPlayPause = $controller.children('[data-crosscover-player]');
$navPlayPause.on('click.' + namespace, function(event) {
$(this).blur();
return __.playToggle.call(_this, $item, $(this));
});
$navPrev.on('click.' + namespace, function(event) {
$(this).blur();
return __.toggle.call(_this, $item, 'prev');
});
$navNext.on('click.' + namespace, function(event) {
$(this).blur();
return __.toggle.call(_this, $item, 'next');
});
},
playToggle: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
var $navPlayPause = $this.find('[data-crosscover-player]');
if (options.autoPlay) {
options.autoPlay = false;
$navPlayPause
.removeClass(__.settings.playerActiveClass)
.addClass(options.playClass);
return __.autoPlayStop.call(_this);
} else {
options.autoPlay = true;
$navPlayPause.addClass(__.settings.playerActiveClass);
return __.autoPlayStart.call(_this, $item);
}
},
toggle: function($item, setting, num) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
__.hide.call(_this, $item);
if (setting === 'next') {
__.settings.currentIndex++;
} else if (setting === 'prev') {
__.settings.currentIndex--;
} else if (setting === 'dots') {
__.settings.currentIndex = num;
}
if (__.settings.currentIndex >= $item.length) {
__.settings.currentIndex = 0;
} else if (__.settings.currentIndex <= -1) {
__.settings.currentIndex = $item.length - 1;
}
__.autoPlayStart.call(_this, $item);
return __.show.call(_this, $item);
},
show: function($item) {
var $this = $(this);
var options = $this.data(namespace).options;
if(options.dotsNav) {
$this
.children('.' + __.settings.dotsNavClass)
.children('li')
.eq(__.settings.currentIndex)
.addClass('is-active')
.children('button')
.prop('disabled', true);
}
return $item
.eq(__.settings.currentIndex)
.addClass(__.settings.coverActiveClass)
.removeClass(__.settings.coverWaitClass)
.addClass(options.inClass)
.csscallbacks('animationEnd',function() {
$(this)
.removeClass(options.inClass + ' ' + __.settings.coverWaitClass)
.addClass(__.settings.coverActiveClass);
});
},
hide: function($item) {
var $this = $(this);
var options = $this.data(namespace).options;
if(options.dotsNav) {
$this
.children('.' + __.settings.dotsNavClass)
.children('li')
.eq(__.settings.currentIndex)
.removeClass('is-active')
.children('button')
.prop('disabled', false);
}
return $item
.eq(__.settings.currentIndex)
.removeClass(__.settings.coverActiveClass)
.addClass(options.outClass)
.csscallbacks('animationEnd', function() {
$(this)
.removeClass(options.outClass + ' ' + __.settings.coverActiveClass)
.addClass(__.settings.coverWaitClass);
});
},
autoPlayStart: function($item) {
var _this = this;
var $this = $(this);
var options = $this.data(namespace).options;
if (options.autoPlay) {
__.autoPlayStop.call(_this);
__.settings.timer = setTimeout(function() {
__.toggle.call(_this, $item, 'next');
__.autoPlayStart.call(_this, $item);
}, options.interval);
}
return _this;
},
autoPlayStop: function() {
return clearTimeout(__.settings.timer);
},
currentIndex: function() {
return __.settings.currentIndex;
}
};
$.fn.crosscover = function(method) {
if (__[method]) {
return __[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return __.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.' + namespace);
}
};
$.fn.csscallbacks = function(type, callback){
var _animationStart = 'animationstart webkitAnimationStart oAnimationStart';
var _animationEnd = 'animationend webkitAnimationEnd oAnimationEnd';
var _transitionEnd = "transitionend webkitTransitionEnd oTransitionEnd";
if(type === 'animationStart'){
type = _animationStart;
} else if(type === 'animationEnd'){
type = _animationEnd;
} else if(type === 'transitionEnd'){
type = _transitionEnd;
}
return this.each(function(index) {
var $this = $(this);
$this.on(type, function(){
$this.off(type);
return callback.call(this);
});
});
};
}));
Its fixed, i just load my content in the #content div and i changed every 'href' to #Home (or name i like) in combination with Benalman's hashchange script

SinglePage navigation

My website uses onePageNav and scrollTo jquery code. I would like to insert code which correct my position on the website when i click on the same link in the navigation (i scroll mouse up or down but current button (hover) in navigation has not moved yet on to the next one).
OnePageNav code:
;
(function ($, window, document, undefined) {
// our plugin constructor
var OnePageNav = function (elem, options) {
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$nav = this.$elem.find('a');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
currentClass: 'current',
changeHash: true,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollOffset: 0,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function () {
var self = this;
// Introduce defaults that can be extended either
// globally or using an object literal.
self.config = $.extend({}, self.defaults, self.options, self.metadata);
//Filter any links out of the nav
if (self.config.filter !== '') {
self.$nav = self.$nav.filter(self.config.filter);
}
//Handle clicks on the nav
self.$nav.on('click.onePageNav', $.proxy(self.handleClick, self));
//Get the section positions
self.getPositions();
//Handle scroll changes
self.bindInterval();
//Update the positions on resize too
self.$win.on('resize.onePageNav', $.proxy(self.getPositions, self));
return this;
},
adjustNav: function (self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function () {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function () {
self.didScroll = true;
});
self.t = setInterval(function () {
docHeight = self.$doc.height();
//If it was scrolled
if (self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if (docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function ($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function () {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function () {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if ($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos) - self.config.scrollOffset;
}
});
},
getSection: function (windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for (var section in this.sections) {
if ((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function (e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if (!$parent.hasClass(self.config.currentClass)) {
//Start callback
if (self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
$.scrollTo(newLoc, self.config.scrollSpeed, {
axis: 'y',
easing: self.config.easing,
offset: {
top: -self.config.scrollOffset
},
onAfter: function () {
//Do we need to change the hash?
if (self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if (self.config.end) {
self.config.end();
}
}
});
}
e.preventDefault();
},
scrollChange: function () {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if (position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if (!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if (this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
unbindInterval: function () {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function (options) {
return this.each(function () {
new OnePageNav(this, options).init();
});
};
})(jQuery, window, document);
$(function () { // this is the shorthand for document.ready
$(window).scroll(function () { // this is the scroll event for the document
scrolltop = $(window).scrollTop(); // by this we get the value of the scrolltop ie how much scroll has been don by user
if (parseInt(scrolltop) >= 80) // check if the scroll value is equal to the top of navigation
{
$("#navbar").css({
"position": "fixed",
"top": "0"
}); // is yes then make the position fixed to top 0
} else {
$("#navbar").css({
"position": "absolute",
"top": "80px"
}); // if no then make the position to absolute and set it to 80
}
}); //here
}); //here

Add Multiple Elements to Page

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

Categories

Resources