Working with Knockoutjs and jCarouselLite - javascript

sorry to be this forward, but I need to see a working example of Knockoutjs working with jCarouselLite (in jsFiddle please). I can't seem to make it work. Here is an earlier question for me regarding this:
Having trouble making Knockout and jCarouselLite to work
Now, what I did was try it out bare bones outside of my actual project. Here is the code I have:
the HTML:
<h2>Index</h2>
<div id="index-root">
<div class="house-row" data-bind="slide: true">
<div class=" house-row-nav"></div>
<div class="house-row-nav"></div>
<ul data-bind="foreach: images">
<li>
<div class="house-row-box nopadding-left nopadding-right">
<div class="image-wrapper">
<img data-bind="attr: { src: $data.image }" alt="image"><span data-bind="text: $data.image"></span>
</div>
</div>
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>
And the KOjs:
$(document).ready(function () {
var model = new IndexViewModel();
model.init();
ko.applyBindings(model, document.getElementById("index-root"));
});
var IndexViewModel = function () {
var self = this;
self.images = ko.observableArray();
//
// Custom bindings
//
//ko.bindingHandlers.slide = {
// init: function (element) {
// },
// update: function (element, valueAccessor) {
// $(element).jCarouselLite({
// btnNext: ".next",
// btnPrev: ".prev",
// visible: 3,
// speed: 1450,
// mouseWheel: true
// });
// }
//};
//
// Methods
//
self.init = function () {
self.images.push({
image: "/Images/1.png"
});
self.images.push({
image: "/Images/2.png"
});
self.images.push({
image: "/Images/3.png"
});
self.images.push({
image: "/Images/4.png"
});
self.images.push({
image: "/Images/5.png"
});
//$(".house-row").jCarouselLite({
// btnNext: ".next",
// btnPrev: ".prev",
// visible: 3,
// speed: 1450,
// mouseWheel: true
//});
};
};
$(document).ready(function () {
$(".house-row").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
visible: 3,
speed: 1450,
mouseWheel: true
});
});
The commented $(".house-row").jCarouselLite... and ko.bindingHandlers.slide... are the locations I tried initializing jCarouselLite.
A sample in a jsfiddle would really help me clear this.

Here's a first stab at it. I had to put the initial call inside a timer because it was being called before the foreach binding had happened, so the carousel didn't have any contents. A more advanced design would probably incorporate the foreach binding as part of the slide.
The setup call is in the init section because it only happens once. I suggested the update section in your previous thread because I thought there would be a need to handle repeated actions on the carousel and bind its selection to an observable or something. We don't do that here.
ko.bindingHandlers.slide = {
init: function(element) {
setTimeout(function() {
$(element).jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
visible: 3,
speed: 1450,
mouseWheel: true
});
}, 0);
},
update: function(element, valueAccessor) {}
};
$(document).ready(function() {
var model = new IndexViewModel();
model.init();
ko.applyBindings(model, document.getElementById("index-root"));
});
var IndexViewModel = function() {
var self = this;
self.images = ko.observableArray();
//
// Methods
//
self.init = function() {
self.images.push({
image: "/Images/1.png"
});
self.images.push({
image: "/Images/2.png"
});
self.images.push({
image: "/Images/3.png"
});
self.images.push({
image: "/Images/4.png"
});
self.images.push({
image: "/Images/5.png"
});
};
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//rawgit.com/ganeshmax/jcarousellite/master/jquery.jcarousellite.min.js"></script>
<h2>Index</h2>
<div id="index-root">
<div class="house-row" data-bind="slide: true">
<button class="prev">«</button>
<button class="next">»</button>
<ul data-bind="foreach: images">
<li>
<div class="house-row-box nopadding-left nopadding-right">
<div class="image-wrapper">
<img data-bind="attr: { src: $data.image }" alt="image"><span data-bind="text: $data.image"></span>
</div>
</div>
</li>
</ul>
<div class="clearfix"></div>
</div>
</div>

Related

Polymer iron-scroll-threshold not triggering

I want to make a feed that automatically loads items when the bottom of the current page is reached, however the iron-scroll-threshold doesn't trigger. I'm using my api call to fill the items in the template and the restaurants load just fine. Also when I bind a load function to a button it works just fine. It seems that the iron-scroll-threshold never triggers. Can anyone explain to me what I'm missing/doing wrong?
Code:
<iron-scroll-threshold id="threshold" lower-threshold="100" on-lower-threshold="loadMoreData">
<div id="scroller" class="vertical layout center" fill>
<template is="dom-repeat" items="[[restaurants]]" filter="{{computeFilter(searchInput)}}" scroll-target="threshold" on-scroll="_scrollHandler">
<!-- Items -->
</template>
<div class="loadingIndicator" hidden$="[[!loadingRestaurants]]">
<paper-spinner active$="[[loadingRestaurants]]"></paper-spinner> Fetching restaurants</b>
</div>
</div>
</iron-scroll-threshold>
<script>
Polymer({
is: 'my-view2',
properties: {
restaurants:{
type: Array,
value: []
},
offset:{
type: Number,
value: 0
},
limit:{
type: Number,
value: 50
},
loadingRestaurants: Boolean
},
ready: function () {
this.$.requestRestaurants.generateRequest();
},
handleResponse: function (data) {
var self = this;
var response = data.detail.response;
response.forEach(function(restaurant){
self.push('restaurants', restaurant);
});
console.log(this.restaurants);
this.$.threshold.clearTriggers();
},
toggle: function(e) {
console.log(this.$.threshold.top);
var index = "#collapse" + e.model.__data.index;
this.$$(index).toggle();
this.loadMore();
},
loadMore: function() {
console.log("test");
this.offset+=50;
this.limit+=50;
this.$.requestRestaurants.generateRequest();
this.$.threshold.clearLower();
this.$.threshold.clearTriggers();
}
});
The naming was inconsistent
on-lower-threshold="loadMoreData"
loadMore: function()

Using owl-filter.js to filter through owl carousel items

I am using this plugin to filter through items in my owl carousel
But it is not working, I have had various console errors, this is the current one:
"Uncaught ReferenceError: initOwlEvent is not defined"
I have added the jquery.owl-filter.js in the footer of my page, and below this called the plugin using this script tag:
<script>
$(function() {
/* animate filter */
var owlAnimateFilter = function(even) {
$(this)
.addClass('__loading')
.delay(70 * $(this).parent().index())
.queue(function() {
$(this).dequeue().removeClass('__loading')
})
}
$('.btn-filter-wrap').on('click', '.btn-filter', function(e) {
var filter_data = $(this).data('filter');
/* return if current */
if($(this).hasClass('btn-active')) return;
/* active current */
$(this).addClass('btn-active').siblings().removeClass('btn-active');
/* Filter */
initOwlEvent.owlFilter(filter_data, function(_owl) {
$(_owl).find('.item').each(owlAnimateFilter);
});
})
})
</script>
This is how I initiate the owl carousel:
var OwlCarousel = function () {
return {
initOwlEvent: function () {
jQuery(document).ready(function() {
var owl = jQuery(".owl-events");
owl.owlCarousel({
lazyLoad: true,
items: 4,
itemsDesktop : [1000,2],
itemsDesktopSmall : [900,2],
itemsTablet: [600,1],
itemsMobile : [479,1],
slideSpeed: 1000,
autoPlay : 5000
});
});
}
}();
My HTML
<div class="row parallax-counter-v4 parallaxBg" id="row_events">
<div class="content container">
<h2 class="title-v2 title-center">Events</h2>
<div id="filter-container" class="btn-filter-wrap cbp-1-filters-text">
<div data-filter=".event-1" class="btn-filter cbp-filter-item">Main Events</div> |
<div data-filter=".event-2" class="btn-filter cbp-filter-item">The Venue</div> |
<div data-filter=".event-3" class="btn-filter cbp-filter-item">Woodys</div> |
<div data-filter=".event-4" class="btn-filter cbp-filter-item">Activities</div>
</div>
<div class="owl-carousel-v1 owl-work-v1 margin-bottom-50 mobile-margin-bottom-10">
<div class="owl-events">
{exp:su_event:homepage limit="8"} {events}
<div class="item news-v2 cbp-item event-{venue_id}">
<div class="news-v2-badge">
{if thumbnail_url == ""}
<a href="/events/id/{event_id}-{url_name}">
<img alt="" class="img-responsive lazyOwl" src="" />
</a>
{if:else}
<a href="/events/id/{event_id}-{url_name}">
<img alt="" class="img-responsive lazyOwl" src="{thumbnail_url}" />
</a>
{/if}
<p>
<span>{start_date format="%d"}</span>
<small>{start_date format="%M"}</small>
</p>
</div>
<h4>{title}</h4>
<p>{description}</p>
</div>
{/events} {/exp:su_event:homepage}
</div>
</div>
</div>
</div>
I had a similar issue while working with WordPress theme. Owl theme displayed the same error as you have mentioned. I have added jquery at the header and the issue got solved I am not sure whether this will work for you but you can give a try. Also, check if the owl script files are included after jquery.
for me, it's working...
$(function() {
$.fn.owlRemoveItem = function(num) {
var owl_data = $(this).data('owlCarousel');
owl_data._items = $.map(owl_data._items, function(data, index) {
if (index != num) return data;
})
$(this).find('.owl-item').eq(num).remove();
}
$.fn.owlFilter = function(data, callback) {
var owl = this,
owl_data = $(owl).data('owlCarousel'),
$elemCopy = $('<div>').css('display', 'none');
/* check attr owl-clone exist */
if (typeof($(owl).data('owl-clone')) == 'undefined') {
$(owl).find('.owl-item:not(.cloned)').clone().appendTo($elemCopy);
$(owl).data('owl-clone', $elemCopy);
} else {
$elemCopy = $(owl).data('owl-clone');
}
/* clear content */
owl.trigger('replace.owl.carousel', ['<div/>']);
switch (data) {
case '*':
$elemCopy.children().each(function() {
owl.trigger('add.owl.carousel', [$(this).clone()]);
})
break;
default:
$elemCopy.find(data).each(function() {
owl.trigger('add.owl.carousel', [$(this).parent().clone()]);
})
break;
}
/* remove item empty when clear */
owl.owlRemoveItem(0);
owl.trigger('refresh.owl.carousel').trigger('to.owl.carousel', [0]);
// callback
if (callback) callback.call(this, owl);
}
var owl = $('.owl-carousel').owlCarousel({
autoplay: false,
nav: true,
loop: false,
items: 3,
autoplayHoverPause: true,
lazyLoad: true,
margin: 10,
responsiveClass: true,
navText : ["",""],
responsive: {
0: {
items: 1,
nav: true
},
600: {
items: 3,
nav: true
},
1000: {
items: 3,
nav: true,
}
},
});
/* animate filter */
var owlAnimateFilter = function(even) {
$(this)
.addClass('__loading')
.delay(70 * $(this).parent().index())
.queue(function() {
$(this).dequeue().removeClass('__loading')
})
}
$('.btn-filter-wrap').on('click', '.btn-filter', function(e) {
console.log('ddd');
var filter_data = $(this).data('filter');
/* return if current */
if ($(this).hasClass('btn-active')) return;
/* active current */
$(this).addClass('btn-active').siblings().removeClass('btn-active');
/* Filter */
owl.owlFilter(filter_data, function(_owl) {
$(_owl).find('.item').each(owlAnimateFilter);
});
})
})

How do I combine my backbonejs view with jquery

Backbonejs.org says
"— while very deliberately avoiding painting you into a corner by making any decisions that you're better equipped to make yourself."
So I have a BackBone view like this:
var LotsaToys= Backbone.View.extend({
el: '#CaveToy',
events: {
'click .slide': 'slideAnimal'
},
initialize: function (obj) {
this.collection = new Yoyo(obj);
this.render();
},
render: function () {
this.collection.each(function (item) {
this.renderToy(item);
}, this);
},
renderBook: function (item) {
var ToyView = new oneToy({
model: item
});
this.$el.append(ToyView .render().el);
}
});
And simple Jquery code like this:
$(document).ready(function () {
var sudoSlider = $("#slider").sudoSlider({
vertical: true,
continuous: false
});
});
Do I combine these to by simply adding the JQuery code in the slide function?
(Simple Jquery image slider)
slideAnimal: function (event) {
$(document).ready(function () {
var sudoSlider = $("#slider").sudoSlider({
vertical: true,
continuous: false
});
});
});
Im a noob, so please give me a explanation ,not sure what way is 'good practice' or what way would be better to implement..
You need place it after render
render: function () {
this.collection.each(function (item) {
this.renderToy(item);
}, this);
this.slideAnimal();
},
slideAnimal: function() {
this.$("#slider").sudoSlider({
vertical: true,
continuous: false
});
}

Close a div when other is opened Jquery

I'm not very good at JavaScript/jQuery. I have code that opens a dropdown. I want to add code so that when one dropdown is opened the others close automatically.
Here's the script code:
var s;
ShowHideWidget = {
settings : {
clickHere : document.getElementById('clickHere'),
dropdown_login : document.getElementById('dropdown_login')
},
init : function() {
//kick things off
s = this.settings;
this.bindUIActions();
},
bindUIActions : function() {
ShowHideWidget.addEvent(s.clickHere, 'click', function() {
ShowHideWidget.toggleVisibility(s.dropdown_login);
});
},
addEvent : function(element, evnt, funct) {
//addEventListener is not supported in <= IE8
if (element.attachEvent) {
return element.attachEvent('on'+evnt, funct);
} else {
return element.addEventListener(evnt, funct, false);
}
},
toggleVisibility : function(id) {
$(id).animate({
left: "",
height: "toggle"
}, 500, function() {
});
}
};
(function() {
ShowHideWidget.init();
})();
/*Script 2*/
var k;
ShowHideWidget = {
settings : {
clickHere2 : document.getElementById('clickHere2'),
dropdown_signup : document.getElementById('dropdown_signup')
},
init : function() {
//kick things off
k = this.settings;
this.bindUIActions();
},
bindUIActions : function() {
ShowHideWidget.addEvent(k.clickHere2, 'click', function() {
ShowHideWidget.toggleVisibility(k.dropdown_signup);
});
},
addEvent : function(element, evnt, funct) {
//addEventListener is not supported in <= IE8
if (element.attachEvent) {
return element.attachEvent('on'+evnt, funct);
} else {
return element.addEventListener(evnt, funct, false);
}
},
toggleVisibility : function(id) {
$(id).animate({
left: "",
height: "toggle"
}, 500, function() {
});
}
};
(function() {
ShowHideWidget.init();
})();
Here's the HTML code:
<div id="clickHere" class="login_area">Sign up</div>
<div id="clickHere2" class="login_area">Login</div>
<div id="dropdown_login">
<div class="dropdown_login_header">
<div class="beeper_login"></div>
</div>
Hello World 111
</div>
<div id="dropdown_signup">
<div class="dropdown_signup_header">
<div class="beeper_value"></div>
<div class="beeper_signup"></div>
</div>
Hello World 2222
</div>
Add a class to dropdowns div identity them in jquery (say drop-down)
<div id="dropdown_login" class="drop-down">
<div class="dropdown_login_header">
<div class="beeper_login"></div>
</div>
Hello World 111
</div>
<div id="dropdown_signup" class="drop-down">
<div class="dropdown_signup_header">
<div class="beeper_value"></div>
<div class="beeper_signup"></div>
</div>
Hello World 2222
</div>
now you can hide the dropdowns anytime by $('.drop-down').hide() [this hides all the elements those matches drop-down in class name, so beware this name should not be used anywhere for class.]
in your case this code will come in
toggleVisibility : function(id) {
$('.drop-down').hide();
$(id).animate({
left: "",
height: "toggle"
}, 500, function() {
You could wrap the drop downs in an extra div like this:
<div id="clickHere" class="login_area">Sign up</div>
<div id="clickHere2" class="login_area">Login</div>
<div>
<div id="dropdown_login">
<div class="dropdown_login_header">
<div class="beeper_login"></div>
</div>
Hello World 111
</div>
<div id="dropdown_signup">
<div class="dropdown_signup_header">
<div class="beeper_value"></div>
<div class="beeper_signup"></div>
</div>
Hello World 2222
</div>
</div>
Then you could use the siblings() method.
toggleVisibility : function(id) {
$(id)
.siblings().hide()
.end()
.animate({
left: "",
height: "toggle"
}, 500, function() {
});
}
Instead of wrapping the drop downs in an extra div, you could add a class to each of the drop down divs. You could then use that class to filter the siblings. For example:
$(id).siblings('.drop-down').hide();

Knockout, Jquery Dialog and not working autocomplete

I have almost working code, but I can't make autocomplete work in pop-up window.
If I do next thing: when project is running, open Pop-up window and type in FireBug console:
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source: $(this).attr("data-skillsautocomplete") });
});
then everything works perfect.
So, the problem is that I don't know how to pass my jquery function to pop-up window.
Help me with that, please.
JS
ko.bindingHandlers.jqDialog = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).dialog("destroy");
});
setTimeout(function() {
$(element).dialog(options);
}, 0);
}
};
ko.bindingHandlers.openDialog = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
$(element).dialog("open");
} else {
$(element).dialog("close");
}
}
};
ko.bindingHandlers.jqButton = {
init: function(element, valueAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
//handle disposal
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).button("destroy");
});
$(element).button(options);
}
};
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source: $(this).attr("data-skillsAutocomplete") });
});
function pageModel() {
self.selectedVacancyForEdit = ko.observable();
self.skillToAdd = ko.observable();
self.editVacancy = function(){
self.selectedVacancyForEdit(new Vacancy());
//here pop-up window opens
}
self.addSkill = function(){
//adding skill
}
}
UI
....code....
//Pop-up window
<div id="details" data-bind="jqDialog: { autoOpen: false, resizable: true, modal: true, width:'auto'}, template: { name: 'editTmpl', data: selectedVacancyForEdit, if: selectedVacancyForEdit }, openDialog: selectedVacancyForEdit"></div>
<script id="editTmpl" type="text/html">
<fieldset>
<form data-bind="submit: $root.addSkill">
Add skill: <input type="text" data-bind="value: $root.skillToAdd,
valueUpdate: 'blur'"
data-skillsAutocomplete="#Url.Action("SearchSkill", "Home")"
name="search"/>`
</fieldset>
</script>
</div>
try to change
$(":input[data-autocomplete]")
to
$("input[data-autocomplete]")

Categories