Function not firing correctly - javascript

currently I have the JS below. I'm trying to run the slideout.close(); event with smoothstate onStart. My code is below and i'm currently getting an error in the console. Could someone please help me out.
Thanks.
$(document).ready(function() {
slideout();
});
function slideout() {
var slideout = new Slideout({
'panel': document.getElementById('slideout-content'),
'menu': document.getElementById('slideout-nav'),
'padding': 256,
'tolerance': 70,
'side': 'right'
});
$('.mobile-nav__icon').on('click', function() {
slideout.toggle();
});
}
$(function(){
'use strict';
var options = {
prefetch: true,
cacheLength: 2,
onStart: {
duration: 860,
render: function ($container) {
$container.addClass('is-exiting');
smoothState.restartCSSAnimations();
slideout.close();
}
},
onReady: {
duration: 0,
render: function ($container, $newContent) {
$container.removeClass('is-exiting');
$container.html($newContent);
}
},
onAfter: function() {
slideout();
}
},
smoothState = $('#animate-wrapper').smoothState(options).data('smoothState');
});

You've created a global function called slideout, within which you have a local variable called slideout that is the one that refers to a Slideout object - you can't access that local variable from other functions. When you try to use slideout.close() that is looking for a .close() method on the function.
One fix would be to change the name of the variable or function and make the variable global too, so that you can access it anywhere. But adding more globals is messy.
I think it should be fine to combine all of your code into a single document ready handler, so that everything is in the same scope without needing any globals (you would still need to use a different name for the variable).
I can't test the following because I don't have whatever Slideout is, but:
$(document).ready(function() {
'use strict';
var slideout; // variable that is local to the doc ready handler function
// and accessible to all code within that handler
function initSlideout() { // function renamed
slideout = new Slideout({ // assign to variable declared above
'panel': document.getElementById('slideout-content'),
'menu': document.getElementById('slideout-nav'),
'padding': 256,
'tolerance': 70,
'side': 'right'
});
}
initSlideout();
$('.mobile-nav__icon').on('click', function() {
slideout.toggle();
});
var options = {
prefetch: true,
cacheLength: 2,
onStart: {
duration: 860,
render: function ($container) {
$container.addClass('is-exiting');
smoothState.restartCSSAnimations();
slideout.close();
}
},
onReady: {
duration: 0,
render: function ($container, $newContent) {
$container.removeClass('is-exiting');
$container.html($newContent);
}
},
onAfter: function() {
initSlideout();
}
},
smoothState = $('#animate-wrapper').smoothState(options).data('smoothState');
});

Related

I am having trouble understanding the Leader-Line js documentation

I am trying to create code that will draw a line from point a to point b using the leaderline library. https://github.com/anseki/leader-line
It looks like the section I need to reference is under Methods
self = line.show([showEffectName[, animOptions]])
where showEffectName: 'draw' and animOptions: {duration: 500, timing: [0.58, 0, 0.42, 1]}
Here is an example shown using a button to show/hide the line
var line = new LeaderLine(startElement, endElement, {hide: true});
showButton.addEventListener('click', function() { line.show(); }, false);
hideButton.addEventListener('click', function() { line.hide(); }, false);
How do I implement the self= code into the button? I'm not even sure what self= is supposed to mean. The below code does not work
var line = new LeaderLine(startElement, endElement, {hide: true});
line.show() = line.show({showEffectName:'draw'}, {animOptions: {duration: 3000, timing: 'linear'}});
startElement.addEventListener('click', function() { line.show(); });
Here is what you are looking for
line.show('draw', {
animOptions: {
duration: 3000,
timing: [0.5, 0, 1, 0.42]
}
})
And now you can call this in any function
button.addEventListener('click', function() {
line.show('draw', {
animOptions: {
duration: 3000,
timing: [0.5, 0, 1, 0.42]
}
})
});
Your code does not work because you have to put only value like below.
var line = new LeaderLine(startElement, endElement, {hide: true});
startElement.addEventListener("click", function () {
line.show("draw", {duration: 3000, timing: 'linear'});
});

cube portfolio with bootstrap template plugin not working

I am using cubeportfolio.js as part of a bootstrap template. It seems to be working but the custom .js part of the template is causing an error in the console.
The template I am using can be seen here, which is working without errors.
The error is 'Uncaught Error: cubeportfolio is already initialized. Destroy it before initialize again!'
For confidentiality reasons I can't post all the code but I have called the jquery.cubeportfolio.min.js at the bottom of the with the custom .js underneath.
Here is the custom .js
(function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 3
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'mouseleave.cbp': function() {
wrap.removeClass('cbp-l-filters-dropdownWrap-open');
}
});
filtersCallback = function(me) {
wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active');
wrap.find('.cbp-l-filters-dropdownHeader').text(me.text());
me.addClass('cbp-filter-item-active');
wrap.trigger('mouseleave.cbp');
};
} else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('click.cbp', '.cbp-filter-item', function() {
var me = $(this);
if (me.hasClass('cbp-filter-item-active')) {
return;
}
// get cubeportfolio data and check if is still animating (reposition) the items.
if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) {
filtersCallback.call(null, me);
}
// filter the items
gridContainer.cubeportfolio('filter', me.data('filter'), function() {});
});
/*********************************
activate counter for filters
*********************************/
gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() {
// read from url and change filter active
var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href),
item;
if (match !== null) {
item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]');
if (item.length) {
filtersCallback.call(null, item);
}
}
});
})(jQuery, window, document);
You have to destroy it before init:
gridContainer.cubeportfolio('destroy');
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 3
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
It is initialized somewhere else and therefore it throws an error because it doesn't know with which cubeportfolio() instance has to deal.
From the error output I’m pretty sure that you instantiate Cube Portfolio twice for the same element.
If you want to instantiate again the plugin call on that element the method destroy
jQuery('#my-grid').cubeportfolio('destroy');
and then the init method to instantiate again
jQuery('#my-grid').cubeportfolio(options);
If you need further help please send me a link to your website to check your code.

CollapseSidebar is not a function

I am writing a script for a project, it has a function to collapse or open the sidebar on click on hamdurger icon but when I click it gives me error
TypeError: this.CollapseSidebar is not a function
The following is my code:
(function($) {
'use strict';
var Prtm = {
Constants: {
LEFTMARGIN:'315px',
COLLAPSELEFTMARGIN: '63px',
},
PrtmEle:{
BODY: $('body'),
SIDEBAR: $('.prtm-sidebar'),
SIDENAV: $('.sidebar-nav'),
MAIN: $('.prtm-main'),
HEADER: $('.prtm-header'),
CONTENTWRAP: $('.prtm-content-wrapper'),
CONTENT: $('.prtm-content'),
PRTMBLOCK: $('.prtm-block'),
FOOTER: $('.prtm-footer'),
HAMBURGER: $('.prtm-bars'),
},
Init:function(){
this.BindEvents();
},
BindEvents:function(){
this.PrtmEle.BODY.on('click',this.PrtmEle.HAMBURGER,function(){
this.CollapseSidebar();
});
},
CollapseSidebar: function(){
this.PrtmEle.HAMBURGER.toggleClass("prtm-sidebar-closed is-active");
this.PrtmEle.BODY.toggleClass("prtm-sidebar-closed is-active");
this.PrtmEle.SIDEBAR.toggleClass('collapse');
},
};
Prtm.Init();
})(jQuery);
When I change this.CollapseSidebar to Prtm.CollapseSidebar it works properly. What I am doing wrong here and how it can be resolved?
Why it do not work? Because a function() binds its own this.
One thing you can do is to use Arrow function which do not bind its own this - like this:
BindEvents:function(){
this.PrtmEle.BODY.on('click',this.PrtmEle.HAMBURGER,() => {
this.CollapseSidebar();
});
}
Inside you click function this will refer to the window - so either you can create a temporary variable like the below or use the arrow function:
BindEvents:function() {
let $this = this;
this.PrtmEle.BODY.on('click',this.PrtmEle.HAMBURGER,function() {
$this.CollapseSidebar();
});
}

Get value of snap.svg object in backbone view

In the following code I want to create the functionality of a like button when the svg symbol is clicked. I am having trouble getting the value of sPaper, sPolyFill and sPolyEmpty.
So far as is they return undefined.
I need to integrate the symbolAnim function into the like and unlike function. How can I do this?
var LikeButtonView = BaseButtonView.extend({
template: _.template($('#like-button-test').html()),
sPaper: null,
sPolyFill: null,
sPolyEmpty: null,
initialize: function (options) {
BaseButtonView.prototype.initialize.apply(this, [options]); // inherit from BaseButtonView
this.butn = $("button.heart-icon", this.$el);
this.sPaper = Snap(heartIcon.get(0));
this.sPolyFill = sPaper.select('.symbol-solid');
this.sPolyEmpty = sPaper.select('.symbol-empty');
},
like: function () {
console.log("Like clicked");
if (this.butn.hasClass("isLiked")) {
this.unlike();
} else if (this.butn.hasClass("unliked")){
this.butn.removeClass("unLiked");
this.butn.addClass("isLiked");
this.addBlur();
}
},
unlike: function () {
this.butn.removeClass('isLiked');
this.butn.addClass("unLiked");
this.addBlur();
},
symbolAnim: function(heartIcon, isLiked) {
if (isLiked === false) {
sPolyFill.animate({ transform: 't9,0' }, 300, mina.easeinout);
sPolyEmpty.animate({ transform: 't-9,0' }, 300, mina.easeinout);
} else {
sPolyFill.animate({ transform: 't0,0'}, 300, mina.easeinout);
sPolyEmpty.animate({ transform: 't0,0' }, 300, mina.easeinout);
}
}
});
Ok so I got the object by targeting this.butn
initialize: function (options) {
BaseButtonView.prototype.initialize.apply(this, [options]); // inherit from BaseButtonView
this.butn = $("button.heart-icon", this.$el);
this.svgNode = this.butn.find("svg").get(0);
this.sPaper = Snap(this.svgNode);
this.sPolyFill = this.sPaper.select('.symbol-solid');
this.sPolyEmpty = this.sPaper.select('.symbol-empty');
console.log(this.sPaper);
Now I need to implement the functionality of symbolAnim in the like and unlike funcitons
For my like button function, which is triggered in the event has as "click selector": "like", I have come up with the following. However this only works once. So when I click the button the first time it adds the class liked and removes the class unliked, which is the default for the html element. Then when it is clicked again, it removes the liked class and adds the unliked class. So far it works as desired.
The problem is when I try to click it again, to like it again, and nothing happens. It doesn't call the like function anymore and the class remains the unliked.
What is causing this problem and how can I fix it?
like: function () {
if (this.butn.hasClass("liked")) {
this.unlike();
} else if (this.butn.hasClass("unliked")) {
this.controller();
console.log("Like clicked");
}
},
controller: function () {
this.butn.removeClass("unliked");
this.butn.addClass("liked");
this.sPolyFill.animate({ transform: 't9,0' }, 300, mina.easeinout);
this.sPolyEmpty.animate({ transform: 't-9,0' }, 300, mina.easeinout);
},
unlike: function () {
this.butn.removeClass('liked');
this.butn.addClass("unLiked");
this.sPolyFill.animate({ transform: 't0,0'}, 300, mina.easeinout);
this.sPolyEmpty.animate({ transform: 't0,0' }, 300, mina.easeinout);
console.log("Unliked");
}

Accessing elements in object

I'm having trouble accessing some elements in an object.
Here in my view file (aka HTML page), I'm initializing the c App.
//Yh script tags are wrapped around this
$(function() {
App.initialize();
});
Then in my JS file (this is a simple form of what I'm actually working on):
window.App = {
el: {
slider: $("#form-slider"),
allSlides: $(".slide")
},
initialize: function() {
this.ProductNewEvents();
//bla bla
// and so on
},
slideTiming: 800,
slideWidth: 790,
delegat etc
ProductNewEvents: function() {
//A whole bunch of events
this.el.slider.click(function() {
alert("Why you no work");
});
$("#form-slider").click(function() {
alert("Why you work");
});
},
some other objs
};
My problem here is I cannot call this.el.allSlides.some jQuery events or this.el.slider. Let's say animate or click in any of the objects. I have to fetch it from the DOM to bind any event to an element e.g. $(".slide").animate.
It depends what you are doing, since I can't see all of your code. When you access your App.el.slider property it holds a reference to $('#slider') at the time it was created. To overcome this your code may have to look something like:
window.App = {
el: {
slider: function(){
$("#form-slider");
},
allSlides: function(){
$(".slide");
}
},
initialize: function() {
this.ProductNewEvents();
//bla bla
// and so on
},
slideTiming: 800,
slideWidth: 790,
//delegat etc
ProductNewEvents: function() {
//A whole bunch of events
},
//some other objs
}
App.el.slider();

Categories