Slider Pro Slide Count - javascript

Using slider-pro, I am having trouble getting slide count for the number of slides inside the carousel. I have looked at this solution, but am having no luck. My code looks like this:
$(document).ready(function($) {
$('.slider-pro').sliderPro();
});
var slider = $( this ).data( 'sliderPro' );
$(this).append('<div class="counter"><span class="active">'+ (parseInt(slider.getSelectedSlide()) + 1) +'</span>/'+slider.getTotalSlides()+'</div>');
slider.on( 'gotoSlide', function( event ) {
$(this).find('.counter .active').text(event.index + 1);
});
But I get a console error:
TypeError: slider is undefined, can't access property "getSelectedSlide" of it
I am not much of a jquery guy, so I'm not sure why it is giving me this error when in fact the property getSelectedSlide is defined in the jquery.sliderPro.js file. Perhaps I'm not calling it correctly or need to bind the property to a class or id. I'm not sure. I've tried both, but nothing seems to work.
Thanks so much!
Unfortunately, I'm using the class selector to initialize multiple sliders on the same page with the same parameters. I don't want to use id because I will have to create a unique id for every slider instance, which I don't want and will become unmanageable. I also cannot dynamically generate an id for each slider. An example page is here:
BFMagazine
Right now, I have to hardcode the slider number/total into every slide, which isn't ideal.
The relevant Slider-Pro js used is:
$(document).ready(function($) {
$('.slider-pro').sliderPro({
width: '100%',
arrows: true,
fadeArrows: false,
buttons: false,
fade: true,
fadeDuration: 200,
thumbnailPosition: 'bottom',
thumbnailWidth: 75,
thumbnailHeight: 75,
autoplay: false,
fullScreen: false,
breakpoints: {
480: {
thumbnailWidth: 40,
thumbnailHeight: 40
}
}
});
$.each('.slider-pro', function() {
var slider = $('.slider-pro').data('sliderPro');
$('.slider-pro').append('<div class="counter"><span class="active">' + (parseInt(slider.getSelectedSlide()) + 1) +
'</span>/' + slider.getTotalSlides() + '</div>');
slider.on('gotoSlide', function(event) {
$('.slider-pro').find('.counter .active').text(event.index + 1);
});
});
});
I'm getting a console error:
TypeError: cannot use 'in' operator to search for 'length' in '.slider-pro'
I am using jquery-2.1.4.min.js
Any suggestions would be greatly appreciated.
Thanks so much!

It's a simple issue actually the code you have found is missing some other details regarding how it's being used; that code need to be used inside an object or event handler context so this will refer to the object but in your case you are trying to use it outside so there is no context for this therefore we can't use it as such.
Anyway as you have told you are new to jquery that's fine; what you need to do is instead of using this use the css selector directly if you are "outside", so you have
var slider = $('.slider-pro').data( 'sliderPro' );
// here this is not ok as it is "outside"
$('.slider-pro').append('<div class="counter"><span class="active">'+ (parseInt(slider.getSelectedSlide()) + 1)
+'</span>/'+slider.getTotalSlides()+'</div>');
slider.on('gotoSlide', function( event ) {
$(this).find('.counter .active').text(event.index + 1);
// here this is ok as it is "inside"
});
Update:
You were almost there but instead of using this each you were needed to use this each, the difference between the two is that the second one specially used for Dom nodes and you can use this magic inside to refer to each item without actually giving them any explicit property like ids
$('.slider-pro').each(function(index, element) {
//using $(element) instead of $(this) should work too
$(this).sliderPro({
//..options
});
var slider = $(this).data('sliderPro');
$(this).append('<div class="counter"><span class="active">' + (parseInt(slider.getSelectedSlide()) + 1) +
'</span>/' + slider.getTotalSlides() + '</div>');
slider.on('gotoSlide', function(event) {
$(this).find('.counter .active').text(event.index + 1);
// finds only the .counter and .active inside the current slider divsnot touching .counter and .active of other slider divs
});
});
A brief explanation would be, the $(selector).each(..) loops over all the Dom nodes that match the selector and gives you a context this that will always refer to the current item of the iteration but only within the scope of each function.For instance if matched items are a set of <div>s then you can refer to each <div> individually

Related

tooltip doesn't work in a table cell

My question might seems long, but I am trying to give relevant information in detail so please bear with me.
I am using tooltipster tooltip plugin (http://iamceege.github.io/tooltipster/) on my website. However my question is more related to JS instead of tooltipster plug in. I am easily able to integrate the tooltip plugin on my website and it is working just fine on images, buttons, etc where the content is static. However, I am populating tables dynamically based on the JSON response and I can't get the tooltip working on the table cells.
First I thought there might be some problem with the plugin. In a flash I switched to bootstrap inbuilt tooltip and I am facing the same problem. I can get bootstrap tooltip to work on other other elements apart from the table cells.
Here is my JS where I am adding the class customToolTip
function addBetTypeProductsToLegend(table) {
var betType = $.data(table, 'BetTableData').betType,
legendRow = $.data(table, 'BetTableData').legendRow,
productNotFount = true,
td;
$.each(betType.products, function(index,value) {
var betTypeHint = 'betTypeId_' + value.id + '_hint';
td = element.create('td');
element.setId(td, value.id);
element.setClassName(td, 'customToolTip'); // adding customToolTip class
element.setTitle(td, window[ 'betTypeId_' + value.id + '_hint']); // setting respective title tags
element.setInnerHtml(td, getBrandBetName(value.name));
legendRow.appendChild(td);
productNotFount = false;
});
// Racing Specials
td = element.create('td');
element.setId(td, betType.id);
element.setInnerHtml(td, betType.name);
if (productNotFount) legendRow.appendChild(td);
}
This is how I am assigning class name and title attributes
var element = {
create: function(htmlIndentifier) {
return document.createElement(htmlIndentifier);
},
setClassName: function(element, className) {
element.className = className;
},
setTitle: function(element, title) {
element.title = title;
}
}
JS plugin initialization
$(document).ready(function() {
$('.customToolTip').tooltipster({
animation: 'fade',
delay: 400,
theme: 'tooltipster-IB',
touchDevices: false,
trigger: 'hover'
});
});
So the above doesn't apply to the table cell I tried to use bootstrap tooltip and initialize the function like this.
$(".customToolTip").tooltip({
placement : 'top'
});
It works fine for other elements apart from table cells.
I tried to set padding as well for tooltip as well
$('.customToolTip').each(function(e) {
var p = $(this).parent();
if(p.is('td')) {
$(this).css('padding', p.css('padding'));
p.css('padding', '0 0');
}
$(this).tooltip({
placement: 'top'
});
});
I followed couple of other posts where people were facing problem with tooltip and table cells
bootstrap "tooltip" and "popover" add extra size in table
https://github.com/twbs/bootstrap/issues/5687
Seems like I have deal with the layout issue later on first I need to show the custom tooltip instead of default title attribute.
Your initialization starts on document ready, when table does not exist in DOM yet. So $('.customToolTip') does not find those.
What you need is to make function, something like this:
function BindTooltips(target) {
target = target || $(document);
target.find('.customToolTip').tooltipster({
animation: 'fade',
delay: 400,
theme: 'tooltipster-IB',
touchDevices: false,
trigger: 'hover'
});
}
And launch it on document ready, so it will find all .customToolTip in your document.
Then after your table is being inserted into dom launch this function again and provide container (table) as argument.

Creating custom slider in jQuery

I'm trying to create a custom slider using jQuery only I'm unsure on the best practice for how ot make this work.
My slider has 3 slides and a controls section each relating to a slide (1, 2, 3).
When a control is clicked I've got my slide fading out only I'm unsure on how to say if X control was clicked, add the active class to the relevant slide?
Ive made a fiddle to explain which i hope helps, what i need however is an explanation of the best practice in doing this?
Sorry if the questions hard to understand!
What I'm using to fade out my current slide, but then once its gone I cant rely on the active class to say add a class to the next element?
$('.ctrl-one').click(function(){
$('.active .slide-img').animate({
'marginRight' : "-=350px"
}, 500, 'easeOutQuint', function(){
$('.active .description').fadeOut().promise().done(function(){
$(this).parent().removeClass('active');
});
});
});
http://jsfiddle.net/Esm97/
I guess this is what you need,try this code , but am sure you can find a lot different methods.
$('.controls a').click(function() {
var current = $(this).attr('class').replace('ctrl-', '');
if (!$('.sector-banner .' + current).hasClass('active')) {
$('.active').animate({
'marginRight': "-=350px"
}, 500, 'linear', function() {
$(this).fadeOut().promise().done(function() {
$(this).css('margin-right',0);
$(this).removeClass('active');
$('.sector-banner .' + current).addClass('active');
$('.sector-banner .' + current).fadeIn();
});
});
}
});

Appending hash/subpage to URL when loading content in expanding divs

I'm loading in separate .html documents inside divs with this code:
JS
$('.thumbnail').click(function() {
var idStr = ("project/"+$(this).attr('id')) + " #projectcontainer";
$('#projectcontainer').animate({opacity:0});
$('#projectcontainer').hide().load(idStr,function(){
$(this).slideDown(500).animate({opacity:1}, function() {
$.scrollTo('#gohere',800);
$('#close').fadeIn(500).css({'display': 'block', 'height': '25px'});
});
});
});
HTML
<div class="thumbnail" id="atmotype.html">
<img src="image.whatever">
</div>
It all works as intended but I also wanna append an ID when you open a project, and also be able to link directly to said content (already expanded in the div). I've been trying around and can't come up with a solution, and that being said I'm pretty awful with JS in general.
Would really appreciate if someone could enlighten me on how this works.
Right now when you click your .thumbnail element, it is firing your click() event and using $(this).attr('id') for the hash/scroll. To make this run when the page load, you should probably break it out to a separate function that takes the ID as a parameter, and then call this function from your click() event as well as a generic page load using a parameter in location.hash.
$(document).ready(function(){
if (location.hash.length>0){
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id){
var idStr = "project/"+ id + "#projectcontainer";
// rest of your code
}
UPDATE:
This is the thing about js it all makes sense when explained but executing it is a bitch. Anyways thanks alot for helping out. Based on your explanation what I get is:
$(document).ready(function() {
if (location.hash.length > 0) {
/* this assumes the page to load is the only thing in the
hash, for example /page.php#project.html */
var hash = location.hash.substring(1); // get hash and remove #
addHashAndScroll(hash); // call function with page name
}
$('.thumbnail').click(function() {
addHashAndScroll($(this).attr('id')); // pass ID value to function
});
}
// this function contains most of your original script
function addHashAndScroll(id) {
var idStr = "project/" + id + "#projectcontainer";
$('#projectcontainer').animate({
opacity: 0
});
$('#projectcontainer').hide().load(idStr, function() {
$(this).slideDown(500).animate({
opacity: 1
}, function() {
$.scrollTo('#gohere', 800);
$('#close').fadeIn(500).css({
'display': 'block',
'height': '25px'
});
});
});
}
I've tried to fiddle around with the closures and whatever minimal experience i have in bug testing js but i keep getting errors originating from this line:
function addHashAndScroll(id) {

How to set marginLeft property using JavaScript?

I used the following code to set the left margin for a div with id=""
document.getElementById('s4-ca').style.marginLeft = '0px';
However getting an error like Object Required!
UPDATE - My code
<script type="text/javascript">
var groupName;
$().SPServices({
operation: "GetGroupCollectionFromUser",
userLoginName: $().SPServices.SPGetCurrentUser(),
async: false,
completefunc: function(xData, Status) {
$(xData.responseXML).find("[nodeName=Group]").each(function()
{
groupName = $(this).attr("Name");
});
}
});
if($.trim(groupName) != 'ABC')
{
document.getElementById('s4-leftpanel').style.display = 'none';
document.getElementById('s4-ca').style.marginLeft = '0px';
}
</Script>
There's nothing wrong with your JavaScript, just give the <div> a matching id property, then it should work fine, i.e.
<div id="s4-ca"></div>
So there reason you're getting the error is because document.getElementById('s4-ca') doesn't find a en element with a matching id, so it's null, and you can't reference the style property on a null object.
Also, when you set the marginLeft there's no need to specify units for zero, you can use just 0.
document.getElementById('s4-ca').style.marginLeft = "0";
Not reproducible: http://jsfiddle.net/VH2z2/
I assume you call document.getElementById before the element is available.
Either include the code on the bottom of the page or in the load event handler, e.g.
window.onload = function() {
document.getElementById('s4-ca').style.marginLeft = '0px';
};
You should not do this if there is other JavaScript code which might set a load event handler (you would overwrite it).
Something like this possibly?
$('#s4-ca').css({ marginLeft: 0 });
the problem is "object requierd"
that means that
document.getElementById('s4-ca')
returns nothing, you must make sure an element with id 's4-ca' exists
$('#s4-ca').css({ marginLeft: 0 });
or
$('#s4-ca').css('margin-left', 0 );
your code is not jquery, but the code above is the way to do this in jquery, both work.
update: your error message probably means that there is no element with id="s4-ca", please check for such an element! see this jsfiddle: http://jsfiddle.net/4DzyW/ where your code just works.
if you want to use jQuery (according to your question's tag)
$("#s4-ca").css('marginLeft','0px');
.css Api of jQuery

Create instances of function

I have a map with a bunch of buttons that show and hide container div's. I don't want to assign the same code to each button because it's all the same.
I was thinking to create a variable when the button is clicked so it could replace a part in the DIV ID (handler?)
So I could refer to #fiche_8_1980_img_container as #fiche_VARIABLE.
Second part of my question is the animation functions I do are all looking like this:
$('#fiche_8_1980_img_container').animate({"opacity" : 1,}, 150, function() {});
Is there a way to put this in an instance or object so I could call it easier?
Here is a piece of code that I use for the button.
$('#button_8_algiers').click(function() {
$('#fiche_8_1980_img_container').css('visibility','visible');
$('#fiche_8_1980_img_container').animate({"opacity" : 1,}, 150, function() {
});
});
If anyone could point me in the right direction it would be great, I don't know where to start looking...
Thank you
would something like this help?
var ficheHandler = {
animateFiche: function(fiche) {
fiche
.css('visibility','visible');
.animate({"opacity" : 1,}, 150, function() {
});
}
}
$('#button_8_algiers').click(function() {
ficheHandler.animateFiche($('#fiche_8_1980_img_container'));
});
Try this which is basically using the help of jQuery chaining so there is no need to cache the object into local variables.
$('#button_8_algiers').click(function() {
$('#fiche_8_1980_img_container').css('visibility','visible');
.animate({"opacity" : 1,}, 150, function() {
});
});
I'm assuming you have control over the HTML. If you have that many buttons with shared functionality, give them the same CSS class, and add a unique identifier in either the rel or data attributes:
$('a.myButton').click(function(e) {
e.preventDefault();
$('#' + $(this).attr('data-target')).fadeIn(150);
});

Categories