Click on object triggers a separate link on the same page - javascript

Hi I am using the bootstrap-tab.js (below) to change tabs and I would like to activate one of the tabs using a separate link on the page. I can quite easily access the second tabs content by linking to "#tab2" but the problem is that the tab system doesn't reflect the change. So my Tab1 is active while Tab2 content is displayed, if that makes sense.
I suspect the the easiest way to do this (given the js) is to trigger the link click from the actual tab using js. Any idea how to achieve this?
!function ($) {
"use strict"; // jshint ;_;
/* TAB CLASS DEFINITION
* ==================== */
var Tab = function (element) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab
, show: function () {
var $this = this.element
, $ul = $this.closest('ul:not(.dropdown-menu)')
, selector = $this.attr('data-target')
, previous
, $target
, e
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ( $this.parent('li').hasClass('active') ) return
previous = $ul.find('.active a').last()[0]
e = $.Event('show', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown'
, relatedTarget: previous
})
})
}
, activate: function ( element, container, callback) {
var $active = container.find('> .active')
, transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if ( element.parent('.dropdown-menu') ) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active.one($.support.transition.end, next) :
next()
$active.removeClass('in')
}
}
/* TAB PLUGIN DEFINITION
* ===================== */
$.fn.tab = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
/* TAB DATA-API
* ============ */
$(function () {
$('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
$(this).tab
('show')
})
})
}(window.jQuery);

Ok, sorry about this I figured it out.
$(document).ready(function(){
$('#scoretab').click(function (e) {
$('#myTab a[href="#tab2"]').tab('show');
})
});

Related

Adding code to existing .js to collapse navbar when click outside menu

Currently I use .js for my sticky navbar in Bootstrap 4.1.3 which works as desired. I have tried to insert a function in the script, which makes the navbar bar collapse on mobile phones if you click outside the menu. However, without luck. https://biogenity.com/RC19/index.html
The code I am currently using is:
$(document).ready(function () {
var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
var stickyHeight = sticky.outerHeight();
var stickyTop = stickyWrapper.offset().top;
if (scrollElement.scrollTop() >= stickyTop) {
stickyWrapper.height(stickyHeight);
sticky.addClass("is-sticky");
}
else {
sticky.removeClass("is-sticky");
stickyWrapper.height('auto');
}
};
$('[data-toggle="sticky-onscroll"]').each(function () {
var sticky = $(this);
var stickyWrapper = $('<div>').addClass('sticky-wrapper');
sticky.before(stickyWrapper);
sticky.addClass('sticky');
$(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
stickyToggle(sticky, stickyWrapper, $(this));
});
stickyToggle(sticky, stickyWrapper, $(window));
});
});
I want to be able to implement a similar function as the following. It is not certain that this is the best solution for "collapse when you click outside the menu".
$(document).on('click', function(event){
var $clickedOn = $(event.target),
$collapsableItems = $('.collapse'),
isToggleButton = ($clickedOn.closest('.navbar-toggle').length == 1),
isLink = ($clickedOn.closest('a').length == 1),
isOutsideNavbar = ($clickedOn.parents('.navbar').length == 0);
if( (!isToggleButton && isLink) || isOutsideNavbar ) {
$collapsableItems.each(function(){
$(this).collapse('hide');
});
}
});
Thanks in advance.
Based on your code, try this:
$(document).click(function (event) {
var clickedOn = $(event.target),
isNavbar = clickedOn.hasClass('navbar'),
// Target only nav links not all links
isNavbarLink = clickedOn.closest('.nav-link').length == 1,
navbarCollapse = $('.navbar-collapse'),
isNavbarOpen = navbarCollapse.hasClass('show');
// if its not navbar and navbar is opened
if (!isNavbar && isNavbarOpen) {
// if the user is not cliking on the nav links
if (!isNavbarLink) {
// thes close the navbar
navbarCollapse.collapse('hide');
}
}
});

Binding a click event (B) after an initial click event (A) causes event B to fire immediately

http://codepen.io/oliecs/pen/womLPJ
var nav = {
init: function () {
console.log('nav init');
$nav = $('nav');
$navIcon = $('.nav-icon');
$navIcon.on('click',function(){
nav.show();
})
},
show: function () {
console.log('nav show');
$nav.addClass('active');
$_DOCUMENT.on('click.navisopen',function(){ //document is a global variable
nav.close();
})
},
close: function () {
console.log('nav close');
$nav.removeClass('active');
$_DOCUMENT.off('.navisopen');
}
};
I feel the pen describes this better than I can. I want to click the nav-icon to open the nav, then any clicks after this will close the nav. However, the close event is fired instantly after the first click, resulting in the nav opening and closing instantly. I don't know how to make this sequential.
Updated js file..Use this code
var ecs= {};
ecs.common = (function($) {
var $_DOCUMENT = $(document),
$_WINDOW = $(window),
$nav = $('nav'),
$navIcon = $('.nav-icon');
var nav = {
init: function () {
console.log('nav init');
$nav = $('nav');
$navIcon = $('.nav-icon');
$navIcon.on('click',function(){
nav.show();
})
},
show: function () {
console.log('nav show');
$nav.addClass('active');
// $_DOCUMENT.on('click.navisopen',function(){
// nav.close();
// })
},
close: function () {
console.log('nav close');
$nav.removeClass('active');
$_DOCUMENT.off('.navisopen');
}
};
//--------------------
// DOM Ready
//--------------------
$(function() {
nav.init();
});
$(document).mouseup(function (e) {
var container = $(".nav-icon");
if (!container.is(e.target) && container.has(e.target).length === 0) {
/* if the target of the click isn't the container && nor a descendant of the container */
$nav.removeClass('active');
}
});
})(jQuery);
You need to
$navIcon.on('click',function(event){
event.stopPropagation();
nav.show();
})
Because the first click is bubbling up the DOM all the way to the document where that event handler is triggered.

How to set fadeout or timeout to alert sucess & warning boxes in opencart 2.2?

I want to set timeout to alert boxes in opencart 2.2. It should disappear after some seconds. I was trying in this code, but didnt work out. Or is this possible if click anywhere in the page the popup should disappear? need help.
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.5'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
Thanks in advance.
alert is the class that opencart uses while displaying error or success message, go to catalog/view/javascript/common.js,
at the end of code add
setTimeout(function(){ $('.alert').fadeOut() }, 5000);
you can change the time parameter based on your requirement.

Magento Jquery Bootstrap and Prototype conflict? nav-tabs dont work

I use Magento 1.9.2.4 and the following Theme
https://github.com/webcomm/magento-boilerplate
The description of it is "HTML5 Twitter Bootstrap 3.1 Magento Boilerplate Template"
It works fine with everything else of "Bootstrap responsive".
My problem is, that all of the following on this Site did not work on my
Installation:
http://www.w3schools.com/bootstrap/bootstrap_tabs_pills.asp
And "did not work" means you can click on next tab but the border and highlighting and so on is still on the first tab.
Same thing on "nav-pills" of Bootstrap.
In this Boilerplate there is a Workaround for Bootstrap dropdown:
jQuery.noConflict();
;(function ($) {
'use strict';
function Site(settings) {
this.windowLoaded = false;
}
Site.prototype = {
constructor: Site,
start: function () {
var me = this;
$(window).load(function () {
me.windowLoaded = true;
});
this.attach();
},
attach: function () {
this.attachBootstrapPrototypeCompatibility();
this.attachMedia();
},
attachBootstrapPrototypeCompatibility: function () {
/*// Bootstrap and Prototype don't play nice, in the sense that
// prototype is a really wacky horrible library. It'll
// hard-code CSS to hide an element when a hide() event
// is fired. See http://stackoverflow.com/q/19139063
// To overcome this with dropdowns that are both
// toggle style and hover style, we'll add a CSS
// class which has "display: block !important"
$('*').on('show.bs.dropdown show.bs.collapse active nav-tabs.active', function (e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse nav-tabs', function (e) {
$(e.target).removeClass('bs-prototype-override');
});*/
var isBootstrapEvent = false;
if (window.jQuery) {
var all = jQuery('*');
jQuery.each(['hide.bs.dropdown',
'hide.bs.collapse',
'hide.bs.modal',
'hide.bs.tooltip',
'hide.bs.popover',
'hide.bs.tab'], function (index, eventName) {
all.on(eventName, function (event) {
isBootstrapEvent = true;
});
});
}
var originalHide = Element.hide;
Element.addMethods({
hide: function (element) {
if (isBootstrapEvent) {
isBootstrapEvent = false;
return element;
}
return originalHide(element);
}
});
},
attachMedia: function () {
var $links = $('[data-toggle="media"]');
if (!$links.length) return;
// When somebody clicks on a link, slide the
// carousel to the slide which matches the
// image index and show the modal
$links.on('click', function (e) {
e.preventDefault();
var $link = $(this),
$modal = $($link.attr('href')),
$carousel = $modal.find('.carousel'),
index = parseInt($link.data('index'));
$carousel.carousel(index);
$modal.modal('show');
return false;
});
}
};
jQuery(document).ready(function ($) {
var site = new Site();
site.start();
});
})(jQuery);
I already asked on github with no response question on github
So the Dropdown of Bootstrap is working.
My Question am i doing anything wrong or am i missing something?
Why does the nav-tabs not work in here?
Adding the "'bower_components/bootstrap/js/tab.js'," tab.js to the gulpfile.js AND
adding the tab class to the script.js solved my Problem with Bootstrap Nav Pills and Tabs.
$('*').on('show.bs.dropdown show.bs. hide.bs.tab hidden.bs.tab', function(e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse', function(e) {
$(e.target).removeClass('bs-prototype-override');
});
At the end the code looks just like this:
jQuery.noConflict();
;(function($) {
'use strict';
function Site(settings) {
this.windowLoaded = false;
}
Site.prototype = {
constructor: Site,
start: function() {
var me = this;
$(window).load(function() {
me.windowLoaded = true;
});
this.attach();
},
attach: function() {
this.attachBootstrapPrototypeCompatibility();
this.attachMedia();
},
attachBootstrapPrototypeCompatibility: function() {
// Bootstrap and Prototype don't play nice, in the sense that
// prototype is a really wacky horrible library. It'll
// hard-code CSS to hide an element when a hide() event
// is fired. See http://stackoverflow.com/q/19139063
// To overcome this with dropdowns that are both
// toggle style and hover style, we'll add a CSS
// class which has "display: block !important"
$('*').on('show.bs.dropdown show.bs. hide.bs.tab hidden.bs.tab', function(e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse', function(e) {
$(e.target).removeClass('bs-prototype-override');
});
},
attachMedia: function() {
var $links = $('[data-toggle="media"]');
if ( ! $links.length) return;
// When somebody clicks on a link, slide the
// carousel to the slide which matches the
// image index and show the modal
$links.on('click', function(e) {
e.preventDefault();
var $link = $(this),
$modal = $($link.attr('href')),
$carousel = $modal.find('.carousel'),
index = parseInt($link.data('index'));
$carousel.carousel(index);
$modal.modal('show');
return false;
});
}
};
jQuery(document).ready(function($) {
var site = new Site();
site.start();
});
})(jQuery);

Stop infinite scroll from jumping to end of page when loading content

I have implemented infinite scroll with isotope on my website and I am having a problem with loading posts. The posts load fine, but lets say I scroll down to load more posts but I am still viewing the posts already there, infinite scroll jumps to the bottom of the page whenever new posts are loaded. How can I stop this behavior and maintain the position on the page even when more posts are loaded?
My script --
$(function () {
var selectChoice, updatePageState, updateFiltersFromObject,
$container = $('.isotope');
////////////////////////////////////////////////////////////////////////////////////
/// EVENT HANDLERS
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Mark filtering element as active/inactive and trigger filters update
$('.js-filter').on( 'click', '[data-filter]', function (event) {
event.preventDefault();
selectChoice($(this), {click: true});
$container.trigger('filter-update');
});
//////////////////////////////////////////////////////
// Sort filtered (or not) elements
$('.js-sort').on('click', '[data-sort]', function (event) {
event.preventDefault();
selectChoice($(this), {click: true});
$container.trigger('filter-update');
});
//////////////////////////////////////////////////////
// Listen to filters update event and update Isotope filters based on the marked elements
$container.on('filter-update', function (event, opts) {
var filters, sorting, push;
opts = opts || {};
filters = $('.js-filter li.active a:not([data-filter="all"])').map(function () {
return $(this).data('filter');
}).toArray();
sorting = $('.js-sort li.active a').map(function () {
return $(this).data('sort');
}).toArray();
if (typeof opts.pushState == 'undefined' || opts.pushState) {
updatePageState(filters, sorting);
}
$container.isotope({
filter: filters.join(''),
sortBy: sorting
});
});
//////////////////////////////////////////////////////
// Set a handler for history state change
History.Adapter.bind(window, 'statechange', function () {
var state = History.getState();
updateFiltersFromObject(state.data);
$container.trigger('filter-update', {pushState: false});
});
////////////////////////////////////////////////////////////////////////////////////
/// HELPERS FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Build an URI to get the query string to update the page history state
updatePageState = function (filters, sorting) {
var uri = new URI('');
$.each(filters, function (idx, filter) {
var match = /^\.([^-]+)-(.*)$/.exec(filter);
if (match && match.length == 3) {
uri.addSearch(match[1], match[2]);
}
});
$.each(sorting, function (idx, sort) {
uri.addSearch('sort', sort);
});
History.pushState(uri.search(true), null, uri.search() || '?');
};
//////////////////////////////////////////////////////
// Select the clicked (or from URL) choice in the dropdown menu
selectChoice = function ($link, opts) {
var $group = $link.closest('.btn-group'),
$li = $link.closest('li'),
mediumFilter = $group.length == 0;
if (mediumFilter) {
$group = $link.closest('.js-filter');
}
if (opts.click) {
$li.toggleClass('active');
} else {
$li.addClass('active');
}
$group.find('.active').not($li).removeClass('active');
if (!mediumFilter) {
if ($group.find('li.active').length == 0) {
$group.find('li:first-child').addClass('active');
}
$group.find('.selection').html($group.find('li.active a').first().html());
}
};
//////////////////////////////////////////////////////
// Update filters by the values in the current URL
updateFiltersFromObject = function (values) {
if ($.isEmptyObject(values)) {
$('.js-filter').each(function () {
selectChoice($(this).find('li').first(), {click: false});
});
selectChoice($('.js-sort').find('li').first(), {click: false});
} else {
$.each(values, function (key, val) {
val = typeof val == 'string' ? [val] : val;
$.each(val, function (idx, v) {
var $filter = $('[data-filter=".' + key + '-' + v + '"]'),
$sort = $('[data-sort="' + v + '"]');
if ($filter.length > 0) {
selectChoice($filter, {click: false});
} else if ($sort.length > 0) {
selectChoice($sort, {click: false});
}
});
});
}
};
////////////////////////////////////////////////////////////////////////////////////
/// Initialization
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Initialize Isotope
$container.imagesLoaded( function(){
$container.isotope({
masonry: { resizesContainer: true },
itemSelector: '.item',
getSortData: {
date: function ( itemElem ) {
var date = $( itemElem ).find('.thedate').text();
return parseInt( date.replace( /[\(\)]/g, '') );
},
area: function( itemElem ) { // function
var area = $( itemElem ).find('.thearea').text();
return parseInt( area.replace( /[\(\)]/g, '') );
},
price: function( itemElem ) { // function
var price = $( itemElem ).find('.theprice').text();
return parseInt( price.replace( /[\(\)]/g, '') );
}
}
});
var total = $(".next a:last").html();
var pgCount = 1;
var numPg = total;
// jQuery InfiniteScroll Plugin.
$container.infinitescroll({
contentSelector : '.isotope',
speed : 'fast',
behavior: 'simplyrecipes',
navSelector : '#pagi', // selector for the paged navigation
nextSelector : '#pagi a.next', // selector for the NEXT link (to page 2)
itemSelector : '.item', // selector for all items you'll retrieve
animate: true,
debug: true,
loading: {
selector: '#infscr-loading',
finishedMsg: 'No more content to load.'
}
},
// Trigger Masonry as a callback.
function( newElements ) {
pgCount++;
if(pgCount == numPg) {
$(window).unbind('.infscr');
$container.isotope('reload');
$container.append( newElements ).isotope( 'appended', newElements, true );
$('#infscr-loading').find('em').text('No more content to load.');
$('#infscr-loading').animate({
opacity: 1
}, 200);
setTimeout(function() {
$('#infscr-loading').animate({
opacity: 0
}, 300);
});
} else {
loadPosts(newElements);
}
});
});
function loadPosts(newElements) {
// Hide new posts while they are still loading.
var newElems = $( newElements ).css({ opacity: 0 });
// Ensure that images load before adding to masonry layout.
newElems.imagesLoaded(function() {
// Show new elements now that they're loaded.
newElems.animate({ opacity: 1 });
$container.isotope( 'appended', newElems, true );
});
}
//////////////////////////////////////////////////////
// Initialize counters
$('.stat-count').each(function () {
var $count = $(this),
filter = $count.closest('[data-filter]').data('filter');
$count.html($(filter).length);
});
//////////////////////////////////////////////////////
// Set initial filters from URL
updateFiltersFromObject(new URI().search(true));
$container.trigger('filter-update', {pushState: false});
});
});
You can start by overriding the default animate property of infinite-scroll
$container.infinitescroll({
animate:false, //this does just that
});
And about your dublicate entry for every request (or perhaps some requests ),
It has something to do with your backend i.e the way you are offseting the data
Infinite Scroll works great with page numbers i.e it
Sends 2,3,4,5,6 ... So For every request its sends that request.
I think you are using page offset instead , and you will probably end up with duplicate entries .
If you are using php as your receiving end ... this might help
//In your Controller
$temp = ( $page_offset * $per_page );
$offset = $temp - $per_page ;
//In your model
$this->db->query("SELECT * FROM GALLERY OFFSET $offset limit 10");
This is just a rough idea , I hope it helps.
If it does , Care to Check out Sticky Bubble ? - A game available for free on Google Play .
Cheers :)

Categories

Resources