Related
My drop down menu opens in mobile view, but when clicking to close, nothing happens.
I've looked at the JS and examples online on what could be wrong but still cant figure it out. Also not sure which js query needs to be udpated as there are 3 different ones; accordion, collapse and 1.112.min.
Screenshot of dropdown menu error
Code:
<!-- navbar menu -->
<div class="collapse navbar-collapse" id="navbar-menu">
<ul class="nav navbar-nav navbar-right">
<li>Our Story</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Solutions</a>
<ul class="dropdown-menu" id="menu">
<li>Point of Sale (POS)</li>
<li>Business Intelligence & Reporting </li>
<li>Integrations</li>
</ul>
</li>
<li>Our Customers</li>
<li>What's New</li>
<li>Contact</li>
</ul>
</div><!-- /.navbar-collapse -->
jquery collapse
(function($) {
// Constructor
function Collapse (el, options) {
options = options || {};
var _this = this,
query = options.query || "> :even";
$.extend(_this, {
$el: el,
options : options,
sections: [],
isAccordion : options.accordion || false,
db : options.persist ? jQueryCollapseStorage(el.get(0).id) : false
});
// Figure out what sections are open if storage is used
_this.states = _this.db ? _this.db.read() : [];
// For every pair of elements in given
// element, create a section
_this.$el.find(query).each(function() {
new jQueryCollapseSection($(this), _this);
});
// Capute ALL the clicks!
(function(scope) {
_this.$el.on("click", "[data-collapse-summary] " + (scope.options.clickQuery || ""),
$.proxy(_this.handleClick, scope));
_this.$el.bind("toggle close open",
$.proxy(_this.handleEvent, scope));
}(_this));
}
Collapse.prototype = {
handleClick: function(e, state) {
e.preventDefault();
var state = state || "toggle"
var sections = this.sections,
l = sections.length;
while(l--) {
if($.contains(sections[l].$summary[0], e.target)) {
sections[l][state]();
break;
}
}
},
handleEvent: function(e) {
if(e.target == this.$el.get(0)) return this[e.type]();
this.handleClick(e, e.type);
},
open: function(eq) {
if(isFinite(eq)) return this.sections[eq].open();
$.each(this.sections, function(i, section) {
section.open();
})
},
close: function(eq) {
if(isFinite(eq)) return this.sections[eq].close();
$.each(this.sections, function(i, section) {
section.close();
})
},
toggle: function(eq) {
if(isFinite(eq)) return this.sections[eq].toggle();
$.each(this.sections, function(i, section) {
section.toggle();
})
}
};
// Section constructor
function Section($el, parent) {
if(!parent.options.clickQuery) $el.wrapInner('<a href="#"/>');
$.extend(this, {
isOpen : false,
$summary : $el.attr("data-collapse-summary",""),
$details : $el.next(),
options: parent.options,
parent: parent
});
parent.sections.push(this);
// Check current state of section
var state = parent.states[this._index()];
if(state === 0) {
this.close(true)
}
else if(this.$summary.is(".open") || state === 1) {
this.open(true);
} else {
this.close(true)
}
}
Section.prototype = {
toggle : function() {
this.isOpen ? this.close() : this.open();
},
close: function(bypass) {
this._changeState("close", bypass);
},
open: function(bypass) {
var _this = this;
if(_this.options.accordion && !bypass) {
$.each(_this.parent.sections, function(i, section) {
section.close()
});
}
_this._changeState("open", bypass);
},
_index: function() {
return $.inArray(this, this.parent.sections);
},
_changeState: function(state, bypass) {
var _this = this;
_this.isOpen = state == "open";
if($.isFunction(_this.options[state]) && !bypass) {
_this.options[state].apply(_this.$details);
} else {
_this.$details[_this.isOpen ? "show" : "hide"]();
}
_this.$summary.toggleClass("open", state != "close")
_this.$details.attr("aria-hidden", state == "close");
_this.$summary.attr("aria-expanded", state == "open");
_this.$summary.trigger(state == "open" ? "opened" : "closed", _this);
if(_this.parent.db) {
_this.parent.db.write(_this._index(), _this.isOpen);
}
}
};
// Expose in jQuery API
$.fn.extend({
collapse: function(options, scan) {
var nodes = (scan) ? $("body").find("[data-collapse]") : $(this);
return nodes.each(function() {
var settings = (scan) ? {} : options,
values = $(this).attr("data-collapse") || "";
$.each(values.split(" "), function(i,v) {
if(v) settings[v] = true;
});
new Collapse($(this), settings);
});
}
});
//jQuery DOM Ready
$(function() {
$.fn.collapse(false, true);
});
// Expose constructor to
// global namespace
jQueryCollapse = Collapse;
jQueryCollapseSection = Section;
})(window.jQuery);
jquery accordion
(function ($) {
$.fn.accordion = function (options) {
//firewalling
if (!this || this.length < 1) {
return this;
}
initialize(this, options);
};
//create the initial accordion
function initialize(obj, options) {
//build main options before element iteration
var opts = $.extend({}, $.fn.accordion.defaults, options);
//store any opened default values to set cookie later
var opened = '';
//iterate each matched object, bind, and open/close
obj.each(function () {
var $this = $(this);
saveOpts($this, opts);
//bind it to the event
if (opts.bind == 'mouseenter') {
$this.bind('mouseenter', function (e) {
e.preventDefault();
toggle($this, opts);
});
}
//bind it to the event
if (opts.bind == 'mouseover') {
$this.bind('mouseover', function (e) {
e.preventDefault();
toggle($this, opts);
});
}
//bind it to the event
if (opts.bind == 'click') {
$this.bind('click', function (e) {
e.preventDefault();
toggle($this, opts);
});
}
//bind it to the event
if (opts.bind == 'dblclick') {
$this.bind('dblclick', function (e) {
e.preventDefault();
toggle($this, opts);
});
}
//initialize the panels
//get the id for this element
id = $this.attr('id');
//if not using cookies, open defaults
if (!useCookies(opts)) {
//close it if not defaulted to open
if (id != opts.defaultOpen) {
$this.addClass(opts.cssClose);
opts.loadClose($this, opts);
} else { //its a default open, open it
$this.addClass(opts.cssOpen);
opts.loadOpen($this, opts);
opened = id;
}
} else { //can use cookies, use them now
//has a cookie been set, this overrides default open
if (issetCookie(opts)) {
if (inCookie(id, opts) === false) {
$this.addClass(opts.cssClose);
opts.loadClose($this, opts);
} else {
$this.addClass(opts.cssOpen);
opts.loadOpen($this, opts);
opened = id;
}
} else { //a cookie hasn't been set open defaults
if (id != opts.defaultOpen) {
$this.addClass(opts.cssClose);
opts.loadClose($this, opts);
} else { //its a default open, open it
$this.addClass(opts.cssOpen);
opts.loadOpen($this, opts);
opened = id;
}
}
}
});
//now that the loop is done, set the cookie
if (opened.length > 0 && useCookies(opts)) {
setCookie(opened, opts);
} else { //there are none open, set cookie
setCookie('', opts);
}
return obj;
}
;
//load opts from object
function loadOpts($this) {
return $this.data('accordion-opts');
}
//save opts into object
function saveOpts($this, opts) {
return $this.data('accordion-opts', opts);
}
//hides a accordion panel
function close(opts) {
opened = $(document).find('.' + opts.cssOpen);
$.each(opened, function () {
//give the proper class to the linked element
$(this).addClass(opts.cssClose).removeClass(opts.cssOpen);
opts.animateClose($(this), opts);
});
}
//opens a accordion panel
function open($this, opts) {
close(opts);
//give the proper class to the linked element
$this.removeClass(opts.cssClose).addClass(opts.cssOpen);
//open the element
opts.animateOpen($this, opts);
//do cookies if plugin available
if (useCookies(opts)) {
// split the cookieOpen string by ","
id = $this.attr('id');
setCookie(id, opts);
}
}
//toggle a accordion on an event
function toggle($this, opts) {
// close the only open item
if ($this.hasClass(opts.cssOpen))
{
close(opts);
//do cookies if plugin available
if (useCookies(opts)) {
// split the cookieOpen string by ","
setCookie('', opts);
}
return false;
}
close(opts);
//open a closed element
open($this, opts);
return false;
}
//use cookies?
function useCookies(opts) {
//return false if cookie plugin not present or if a cookie name is not provided
if (!$.cookie || opts.cookieName == '') {
return false;
}
//we can use cookies
return true;
}
//set a cookie
function setCookie(value, opts)
{
//can use the cookie plugin
if (!useCookies(opts)) { //no, quit here
return false;
}
//cookie plugin is available, lets set the cookie
$.cookie(opts.cookieName, value, opts.cookieOptions);
}
//check if a accordion is in the cookie
function inCookie(value, opts)
{
//can use the cookie plugin
if (!useCookies(opts)) {
return false;
}
//if its not there we don't need to remove from it
if (!issetCookie(opts)) { //quit here, don't have a cookie
return false;
}
//unescape it
cookie = unescape($.cookie(opts.cookieName));
//is this value in the cookie arrray
if (cookie != value) { //no, quit here
return false;
}
return true;
}
//check if a cookie is set
function issetCookie(opts)
{
//can we use the cookie plugin
if (!useCookies(opts)) { //no, quit here
return false;
}
//is the cookie set
if ($.cookie(opts.cookieName) == null) { //no, quit here
return false;
}
return true;
}
// settings
$.fn.accordion.defaults = {
cssClose: 'accordion-close', //class you want to assign to a closed accordion header
cssOpen: 'accordion-open', //class you want to assign an opened accordion header
cookieName: 'accordion', //name of the cookie you want to set for this accordion
cookieOptions: {//cookie options, see cookie plugin for details
path: '/',
expires: 7,
domain: '',
secure: ''
},
defaultOpen: '', //id that you want opened by default
speed: 'slow', //speed of the slide effect
bind: 'click', //event to bind to, supports click, dblclick, mouseover and mouseenter
animateOpen: function (elem, opts) { //replace the standard slideDown with custom function
elem.next().stop(true, true).slideDown(opts.speed);
},
animateClose: function (elem, opts) { //replace the standard slideUp with custom function
elem.next().stop(true, true).slideUp(opts.speed);
},
loadOpen: function (elem, opts) { //replace the default open state with custom function
elem.next().show();
},
loadClose: function (elem, opts) { //replace the default close state with custom function
elem.next().hide();
}
};
})(jQuery);
Im using django-el-pagination to do lazy loading of entries.
When I click on an entry and then use the browser back button, all of the lazy loading is gone, I tried to add window.history.pushState() but then I only get the current page i.e.?page=4 when I use the browser back button, and all of the entries on top is not loaded.
Is there any way to implement a correct history so that the user is back at the same place when they use the browser back button?
$.endlessPaginate({
paginateOnScroll: true,
paginateOnScrollMargin: 400,
paginateOnScrollChunkSize: 2,
onCompleted: function(context, fragment) {
window.history.pushState(null, null, context.url);
}
});
Edit 1
Here is the JavaScript for the .endlessPaginate function:
'use strict';
(function ($) {
// Fix JS String.trim() function is unavailable in IE<9 #45
if (typeof(String.prototype.trim) === "undefined") {
String.prototype.trim = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
$.fn.endlessPaginate = function(options) {
var defaults = {
// Twitter-style pagination container selector.
containerSelector: '.endless_container',
// Twitter-style pagination loading selector.
loadingSelector: '.endless_loading',
// Twitter-style pagination link selector.
moreSelector: 'a.endless_more',
// Digg-style pagination page template selector.
pageSelector: '.endless_page_template',
// Digg-style pagination link selector.
pagesSelector: 'a.endless_page_link',
// Callback called when the user clicks to get another page.
onClick: function() {},
// Callback called when the new page is correctly displayed.
onCompleted: function() {},
// Set this to true to use the paginate-on-scroll feature.
paginateOnScroll: false,
// If paginate-on-scroll is on, this margin will be used.
paginateOnScrollMargin : 1,
// If paginate-on-scroll is on, it is possible to define chunks.
paginateOnScrollChunkSize: 0
},
settings = $.extend(defaults, options);
var getContext = function(link) {
return {
key: link.attr('rel').split(' ')[0],
url: link.attr('href')
};
};
return this.each(function() {
var element = $(this),
loadedPages = 1;
// Twitter-style pagination.
element.on('click', settings.moreSelector, function() {
var link = $(this),
html_link = link.get(0),
container = link.closest(settings.containerSelector),
loading = container.find(settings.loadingSelector);
// Avoid multiple Ajax calls.
if (loading.is(':visible')) {
return false;
}
link.hide();
loading.show();
var context = getContext(link);
// Fire onClick callback.
if (settings.onClick.apply(html_link, [context]) !== false) {
var data = 'querystring_key=' + context.key;
// Send the Ajax request.
$.get(context.url, data, function(fragment) {
container.before(fragment);
container.remove();
// Increase the number of loaded pages.
loadedPages += 1;
// Fire onCompleted callback.
settings.onCompleted.apply(
html_link, [context, fragment.trim()]);
});
}
return false;
});
// On scroll pagination.
if (settings.paginateOnScroll) {
var win = $(window),
doc = $(document);
doc.scroll(function(){
if (doc.height() - win.height() -
win.scrollTop() <= settings.paginateOnScrollMargin) {
// Do not paginate on scroll if chunks are used and
// the current chunk is complete.
var chunckSize = settings.paginateOnScrollChunkSize;
if (!chunckSize || loadedPages % chunckSize) {
element.find(settings.moreSelector).click();
} else {
element.find(settings.moreSelector).addClass('endless_chunk_complete');
}
}
});
}
// Digg-style pagination.
element.on('click', settings.pagesSelector, function() {
var link = $(this),
html_link = link.get(0),
context = getContext(link);
// Fire onClick callback.
if (settings.onClick.apply(html_link, [context]) !== false) {
var page_template = link.closest(settings.pageSelector),
data = 'querystring_key=' + context.key;
// Send the Ajax request.
page_template.load(context.url, data, function(fragment) {
// Fire onCompleted callback.
settings.onCompleted.apply(
html_link, [context, fragment.trim()]);
});
}
return false;
});
});
};
$.endlessPaginate = function(options) {
return $('body').endlessPaginate(options);
};
})(jQuery);
short answer: no. The whole point of 'endless pagination' is to not reload a (new) page, therefore there is no history.
I'm trying to capture if the enter key has been pressed and execute a search. This is the viewmodel for the search page.
(function ()
{
a.viewModels.userSearch = function (view, params) {
$view = $(view);
var self = a.viewModel({
users: a.collection({
url: '/admin/Account/SearchUsers',
query: {
SearchText: null
}
}).fetch(),
setPageIndex: setPageIndex,
search: search
});
$view.keypress(function (e) {
if (e.keyCode == 13) {
self.search(e);
}
});
function search(e) {
self.users.query.rowCount = 0;
self.users.query.pageIndex = 1;
self.users.fetch();
}
function setPageIndex(e) {
e.preventDefault();
self.users.query.set('pageIndex', $(e.currentTarget).data('page-index'));
self.users.fetch();
}
return self;
}
Now, this works. The problem is that it works only after pressing the 'Enter' key 2 times. Seems like I'm missing something related to the scope but js ain't my cup of tea.
If it is of any help, here goes my view model function:
function viewModel(viewModelConfig) {
var self = kendo.observable($.extend({
busy: 0,
resultMessage: null,
clearResultMessage: clearResultMessage
}, viewModelConfig));
self.bind('change', onChange);
function onChange(change) {
var errorProp, errorMsg, infoProp, infoMsg;
if (change.field.endsWith('.busy')) {
if (self.get(change.field))
self.set('busy', self.busy + 1);
else if (self.busy > 0)
self.set('busy', self.busy - 1);
}
else if (change.field.endsWith('.resultMessage')) {
var data = self.get(change.field);
self.set('resultMessage', data);
}
}
function clearResultMessage(e)
{
if (e) e.preventDefault();
self.set('resultMessage', null);
return false;
}
return self;
}
I have a similar setup on my site, and using MVVM, just add the custom enter binding within the data-bind attribute of the element to link to the function within the view-model you wish to execute.
The code to add the custom binder is as such:
kendo.data.binders.widget.enter = kendo.data.Binder.extend({
init: function(element, bindings, options) {
kendo.data.Binder.fn.init.call(this, element, bindings, options);
var binding = this.bindings.enter;
$(element.element).keyup(function(e) {
if( e.which === 13 )
bindings.get();
});
},
refresh: $.noop
});
I use pjax to ajaxify my menu links. This works fine until I use the browser back button. In my javascript file I use Common Script files (to load all the necessary js files when the user hits the url) and Script files with respect to each menu links (when navigated through pjax)
function myFunction(){
/*All the script files */
}
$(document).ready(function(){
myFunction();
/*pjax menu loading block*/
$(document).on('click', 'a[data-pjax]', function(event) {
$.pjax.click(event, '#pjax-container');
$(document).on('pjax:end', function() {
myFunction();
});
});
});
Now when I navigate to a menu item and try to come back by clicking the browser back button, the script files are getting duplicated (eg: slider images getting duplicated and table sorting not working).How to overcome this issue?
You can implement the url specific loading this way, create a queue of functions which you want to load and unload on pjax complete
The solution is based on js prototyping
// create queue for load and unload
var onLoad = new PjaxExecQueue();
var onUnload = new PjaxExecQueue();
// way to add functions to queue to run on pjax load
onLoad.queue(function() {
someFunction();
});
// way to add functions to queue to unload on pjax load
onUnload.queue(function() {
someOtherFunction();
});
// load function if url contain particular path name
onLoad.queue_for_url(function_name, 'url_section');
// check for url specific function
var URLPjaxQueueElement = function(exec_function, url) {
this.method = exec_function;
if(url) {
this.url = new RegExp(url);
} else {
this.url = /.*/;
}
};
// create a queue object
var PjaxExecQueue = function () {
this.url_exec_queue = [];
this.id_exec_queue = [];
this.fired = false;
this.indicating_loading = false;
this.content = $('#content');
};
PjaxExecQueue.prototype = {
queue: function (exec_function) {
this.url_exec_queue.unshift(new URLPjaxQueueElement(exec_function));
},
queue_for_url: function (exec_function, url_pattern) {
this.url_exec_queue.unshift(new URLPjaxQueueElement(exec_function, url_pattern));
},
queue_if_id_present: function(exec_function, id) {
this.id_exec_queue.unshift(new IDPjaxQueueElement(exec_function, id));
},
fire: function () {
if(this.indicating_loading) {
this.content.removeClass("indicate-loading");
this.indicating_loading = false;
}
if(!this.fired) {
var match_loc = window.location.pathname;
var i = this.url_exec_queue.length;
while(i--) {
this.url_exec_queue[i].fire(match_loc);
}
i = this.id_exec_queue.length;
while(i--) {
this.id_exec_queue[i].fire(match_loc);
}
}
this.fired = true;
},
reset: function() {
this.fired = false;
},
loading: function () {
this.content.addClass("indicate-loading");
this.indicating_loading = true;
this.reset();
},
count: function () {
return exec_queue.length;
},
show: function (for_url) {
for (var i=0; i < exec_queue.length; i++) {
if(for_url) {
if(exec_queue[i].url.test(for_url)) {
console.log("" + exec_queue[i].method);
}
} else{
console.log(exec_queue[i].url + " : " + exec_queue[i].method);
}
}
}
};
// before send
$(document).on('pjax:beforeSend', function() {
onLoad.loading();
onUnload.fire();
});
// after pjax complete
$(document).on('pjax:complete', function() {
onLoad.fire();
onUnload.reset();
});
Im working with some JS code, since Im not front developer im having some issues to figuring out how to trigger an event on JS that normally fires when a link is clicked.
This is the link:
Demo
And the JS function that intercept the click on that link is:
(function (global) {
'use strict';
// Storage variable
var modal = {};
// Store for currently active element
modal.lastActive = undefined;
modal.activeElement = undefined;
// Polyfill addEventListener for IE8 (only very basic)
modal._addEventListener = function (element, event, callback) {
if (element.addEventListener) {
element.addEventListener(event, callback, false);
} else {
element.attachEvent('on' + event, callback);
}
};
// Hide overlay when ESC is pressed
modal._addEventListener(document, 'keyup', function (event) {
var hash = window.location.hash.replace('#', '');
// If hash is not set
if (hash === '' || hash === '!') {
return;
}
// If key ESC is pressed
if (event.keyCode === 27) {
window.location.hash = '!';
if (modal.lastActive) {
return false;
}
// Unfocus
modal.removeFocus();
}
}, false);
// Convenience function to trigger event
modal._dispatchEvent = function (event, modal) {
var eventTigger;
if (!document.createEvent) {
return;
}
eventTigger = document.createEvent('Event');
eventTigger.initEvent(event, true, true);
eventTigger.customData = { 'modal': modal };
document.dispatchEvent(eventTigger);
};
// When showing overlay, prevent background from scrolling
modal.mainHandler = function () {
var hash = window.location.hash.replace('#', '');
var modalElement = document.getElementById(hash);
var htmlClasses = document.documentElement.className;
var modalChild;
// If the hash element exists
if (modalElement) {
// Get first element in selected element
modalChild = modalElement.children[0];
// When we deal with a modal and body-class `has-overlay` is not set
if (modalChild && modalChild.className.match(/modal-inner/) &&
!htmlClasses.match(/has-overlay/)) {
// Set an html class to prevent scrolling
//document.documentElement.className += ' has-overlay';
// Mark modal as active
modalElement.className += ' is-active';
modal.activeElement = modalElement;
// Set the focus to the modal
modal.setFocus(hash);
// Fire an event
modal._dispatchEvent('cssmodal:show', modal.activeElement);
}
} else {
document.documentElement.className =
htmlClasses.replace(' has-overlay', '');
// If activeElement is already defined, delete it
if (modal.activeElement) {
modal.activeElement.className =
modal.activeElement.className.replace(' is-active', '');
// Fire an event
modal._dispatchEvent('cssmodal:hide', modal.activeElement);
// Reset active element
modal.activeElement = null;
// Unfocus
modal.removeFocus();
}
}
};
modal._addEventListener(window, 'hashchange', modal.mainHandler);
modal._addEventListener(window, 'load', modal.mainHandler);
/*
* Accessibility
*/
// Focus modal
modal.setFocus = function () {
if (modal.activeElement) {
// Set element with last focus
modal.lastActive = document.activeElement;
// New focussing
modal.activeElement.focus();
}
};
// Unfocus
modal.removeFocus = function () {
if (modal.lastActive) {
modal.lastActive.focus();
}
};
// Export CSSModal into global space
global.CSSModal = modal;
}(window));
How can i call the function that gets called when the user clicks the link but manually on my page, something like <script>firelightbox(parameters);</script>
Using jQuery will solve this easily
$('.selector').click();
but plain old JavaScript may also have a solution for you
Let's just give your anchor element an Id (to keep things simple)
<a id="anchorToBeClicked" href="#modal-text" class="call-modal" title="Clicking this link shows the modal">Demo</a>
Let's create a function that simulates the click
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("anchorToBeClicked");
cb.dispatchEvent(evt);
}
Now call this function on window.onload
window.onload = function() {
simulateClick();
};
EDIT:
Actually, the code you are using is not working on actual click event of the anchor tag, instead it relies on hash change of Url in your browser window. You can simply invoke that functionality by using
window.onload = function() {
location.hash = '#modal-text'
};
If you are using jQuery, you can trigger the clicking of a link on page load using this code:
$(document).ready(function(){
$('.call-modal').click();
});