Jquery JSON plugin colliding with slick carousel - javascript

I am relatively new to jquery but i need that script to start working properly.
I have an jquery script for reading JSON data from url. It is working by itself but when i try to load data inside slick carousel, carousel stops working. I think that the problem is inside my script. Please help!
My code:
(function($){
$.fn.scores = function() {
liveScores();
};
function liveScores() {
setTimeout(liveScores, 5000);
var jsonData = "http://url";
$.getJSON(jsonData, function(rawJsonData){
var complete =[];
//var realcatCount = rawJsonData.doc[0].data[0].realcategories.length;
for (realCat = 0; realCat <= 3; realCat ++) {
console.log(realCat);
var basePath = rawJsonData.doc[0].data[0].realcategories[realCat]
var tournament = basePath.tournaments[0].name;
var name = basePath.name;
var matchStatus = basePath.tournaments[0].matches[0].status._id;
var homeTeam = basePath.tournaments[0].matches[0].teams.home.name;
var awayTeam = basePath.tournaments[0].matches[0].teams.away.name;
var time = basePath.tournaments[0].matches[0]._dt.time;
var date = basePath.tournaments[0].matches[0]._dt.date;
var homeScore = basePath.tournaments[0].matches[0].result.home;
var awayScore = basePath.tournaments[0].matches[0].result.away;
var teamIdHome = basePath.tournaments[0].matches[0].teams.home.uid;
var teamIdHAway = basePath.tournaments[0].matches[0].teams.away.uid;
complete.push('<div class="slide-wrapper"><h2>'+tournament+'</h2><h4>'+name+'</h4><div class="score">'+homeScore+ ' vs. '+awayScore+'</div><div class="team home-team"><div class="crest crest-home" style="background:url(http://ls.betradar.com/ls/crest/big/'+teamIdHome+'.png) no-repeat center center;"></div><h3>'+homeTeam+'</h3></div><div class="team away-team"><div class="crest crest-away" style="background:url(http://ls.betradar.com/ls/crest/big/'+teamIdHAway+'.png) no-repeat center center;"></div><h3>'+awayTeam+'</h3></div><div class="overlay"></div><img class="bcg" src="images/bg-live.jpg"></div>');
}
console.log(complete);
$('#results').empty().append(complete);
});
};
})(jQuery);
This is the order i load scripts and plugins at the bottom of the page.
<script type="text/javascript" src="js/scores.js"></script>
<script>
$(document).ready(function() {
$().scores();
});
</script>
<script type="text/javascript" src="js/slick.js"></script>
<script>
$(document).ready(function(){
$('.slider').slick({
dots: true,
arrows: false,
infinite: true,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true,
fade: true,
cssEase: 'linear'
});
});
</script>
First i load carousels item (JSON data) and then the slick carousel itself.
And the slick carousel works just fine until i put data from my plugin into it.

The code provided is not very good,
for instance you don't know if there are 3 realcats (0,1,2)
don't use json as a variable name, json is a notation, not an good variable name
$.getJSON(jsonData, function(rawJsonData){
var complete =[];
var realcatCount = rawJsonData.doc[0].data[0].realcategories.length;
for (realCat = 0; realCat <= (realcatCount -1); realcatCount ++) {
console.log(realCat);
var basePath = json.doc[0].data[0].realcategories[realCat]
...
The rest of your code seems ok, but not really good.
Try to walk the json path as less as needed.
this would be:
var match = basePath.tournaments[0].matches[0];
var matchStatus = match .status._id;
var homeTeam = match .teams.home.name;
What you need to do is make sure your html is there BEFORE you bind it. so first generate the carrousel items, and then perform the .slick() function
This way you would get:
// Your existingt code..
$('#results').empty().append(complete);
// AND then slick it.. Delete this code from the seperate code block in your html and move it to here..
$('.slider').slick({
dots: true,
arrows: false,
infinite: true,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true,
fade: true,
cssEase: 'linear'
});
Your problem is that .slick is called BEFORE the html is there (it is derived from a web url)
first create the html, and append it
then do .slick
The resulting (working) code:
https://jsfiddle.net/aeuuymuy/12/

Related

"bxslider jquery" change the slide mode at specified width

like the title i'm using bxslider at my website, actually i'm using vertical thumbnail slide now, but the problem is, it's look ugly when at mobile width, so i want to change it like normal slider with arrow. can you help me how to do that? here is the things i want:
1. at normal using vertical thumb slide
2. when the width triggered at specify width, the thumb is hide (maybe display none at css)
3. Do destroyslider for stopping the vertical thumb slider and change it to normal slider with arrow
4. when the width is normal again, it will switch again to vertical thumb slider
ok here is my jquery:
var mainImage;
$(window).load(function() {
mainImage = $('.product-gallery').bxSlider({
infiniteLoop: false,
hideControlOnEnd: true,
pager: false,
controls: false,
auto: false,
minSlides: 1,
maxSlides: 1,
moveSlides: 1,
mode: 'fade',
adaptiveHeight: true
});
$('.product-gallery-thumbs ul').bxSlider({
infiniteLoop: false,
hideControlOnEnd: true,
pager: false,
auto: false,
minSlides: 4,
maxSlides: 4,
moveSlides: 1,
slideWidth: '100%',
mode: "#{options['product_thumbnail_direction']}",
slideMargin: 10,
onSliderLoad: function(currentIndex) {
$('.product-gallery-thumbs ul li').eq(0).addClass('active')
}
});
$('.product-gallery-thumbs ul li').each(function() {
$(this).click(function() {
$(this).addClass('active').siblings().removeClass('active');
mainImage.goToSlide($(this).index());
});
});
});
when do destroy :
mainImage.destroySlider();
here is normal slider with arrow:
mainImage.bxSlider({
mode: 'fade',
captions: true,
slideWidth: 600
});
UPDATE :
I try to did this, when do destroy is work, but when switching to normal arrow slider it doesn't work. Hope you guys can help me fix this
$(document).ready(function(){
setMaxWidth(767px);
mainImage.destroySlider();
function setMaxWidth(767px) {
mainImage.bxSlider({
mode: 'fade',
captions: true,
slideWidth: 600
});
})
bx.reloadSlider() Method
The method destroySlider() returns bxSlider as it was initially so don't use it if you want to change bxSlider after a reload, instead use reloadSlider(). Besides the obvious (reloading bxSlider), you can load a different set of options. Note: There are 2 Object Literals:
var cfgA = {...} and var cfgB = {...}
Each of them has key/value pairs (or properties) that are from the bxSlider API. When calling .bxSlider(), simply load one of configurations:
var bx = $('.bx').bxSlider(cfgA);
onSliderResize Callback
As far as slider plugins go, bxSlider isn't the most stable and it can get buggy as browsers update and bxSlider stagnates at v.4.2.12, but there's one thing bxSlider excels in is callbacks. I've written complex programs that are controlled by bxSlider callbacks because they are reliable and never break. In this demo onSliderResize call the function reloadBX(currentIndex). **Note: ** the absence of parenthesis on reloadBX():
onSliderResize: reloadBX
reloadBX(currentIndex)
This is the heart of the Demo. For demonstration purposes I've bound the function to a convenient button. When testing the Demo, you should expect the following by either clicking the RELOAD button, or resizing bxSlider:
Toggling between cfgA and cfgB
Relocates to the position index bxSlider was on before the reload.
Shifts images to adjust at reload to avoid images being stuck halfway.
Details commented in Demo
Demo
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>bxSlider Reload</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.css">
<style>
img {
margin: auto;
display: block;
max-width: 100%;
}
</style>
</head>
<body>
<button class='reload'>RELOAD</button>
<ul class='bx'>
<li>
<img src="https://i.imgur.com/DrEwPH0.jpg">
<img src="https://i.imgur.com/MEPxbq4.jpg">
</li>
<li>
<img src="https://i.imgur.com/6qGdA1e.gif">
</li>
<li>
<img src='https://i.imgur.com/DsM6J8U.gif'>
</li>
<li>
<img src="https://i.imgur.com/sbxyLKX.png">
</li>
<li>
<img src="https://i.imgur.com/DheohWR.gif">
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.min.js"></script>
<script>
// Cfg flag
var AB = 'A';
// Index counter
var idx = 0;
// cfgA
var cfgA = {
mode: 'horizontal',
slideWidth: 320,
adaptiveHeight: true,
onSliderResize: reloadBX
};
// cfgB
var cfgB = {
mode: 'fade',
captions: true,
slideWidth: 160,
adaptiveHeight: true,
onSliderResize: reloadBX
};
// Reference bxSlider instance
var bx = $('.bx').bxSlider(cfgA);
/*
Resize Callback
*/ // Called on resize event
function reloadBX(current) {
// Store current index
idx = current;
// Determine what configuration bx is in
if (AB === "A") {
/* if bx is in cfgA...
|| reload slider with cfgB
*/
bx.reloadSlider(cfgB);
// Shift all img to the left
$('img').css('transform', 'translateX(-25%)');
// Switch cfg flag to B
AB = "B";
// Otherwise...
} else {
// Reload slider with cfgA
bx.reloadSlider(cfgA);
// Shift all img to the right
$('img').css('transform', 'translateX(0)');
// Switch cfg flag to A
AB = "A";
}
// Go back to the index before reload
bx.goToSlide(idx);
}
// Added a reload button for convenient testing
$('.reload').click(function(e) {
// Get the current index and store it
idx = bx.getCurrentSlide();
/* Need to use the .call() function so that the context
|| is changed to bxSlider
*/
reloadBX.call(this, idx);
});
</script>
</body>
</html>

Getting images from itunes rss feed and putting the pics in a bxslider

So I am able to get the images of the albums from the itunes rss by using this code:
$("#parse").click(function (){
$(".bxslider").html("");
var country = $("#country").val();
var number = $("#top").val();
$.get("https://itunes.apple.com/"+country+"/rss/topsongs/limit="+number+"/xml" , function(data){
var itunesArray = $(data).find("entry");
itunesArray.each(function(){
var image = $(this).find("im\\:image").eq(1).text();
var audio = $(this).find("link").eq(1).attr("href");
HTML for my slider:
<div class="slider">
<ul class = "bxslider">
</ul>
</div>
I try to append the html by using this code:
$('.bxslider').append("<li><img src = "+image + " height = '100'
width ='100' >" + "</li>");
Jquery for slider:
$('.bxslider').bxSlider({
mode: 'fade',
//captions: true,
auto: true,
//autoControls: true
pagerCustom: '#bx-pager'
/*minSlides: 2,
maxSlides: 2,
slideWidth: 170,
slideMargin: 10,
ticker: true,
speed: 7000*/
});
I can get the images into the webpage but not inside the slider. I can see the arrows but I am unable to switch images and can see all of them at once. Im supposed to see them one at a time. I do not know whats going on. Any recommendations would be highly appreciated. Thank you!
I will suggest you to initialize your bxSlider inside $.get Ajax success callback i.e. after all images has been added to DOM (exactly after itunesArray.each() loop).
I think you have not posted the entire code but you can just refer below code and take the idea (this code may not work directly as it is):
$("#parse").click(function (){
$(".bxslider").html("");
var country = $("#country").val();
var number = $("#top").val();
$.get("https://itunes.apple.com/"+country+"/rss/topsongs/limit="+number+"/xml" , function(data){
var itunesArray = $(data).find("entry");
itunesArray.each(function(){
var image = $(this).find("im\\:image").eq(1).text();
var audio = $(this).find("link").eq(1).attr("href");
$('.bxslider').append("<li><img src = "+image + " height = '100' width ='100' >" + "</li>");
});//each loop end
$('.bxslider').bxSlider({
mode: 'fade',
//captions: true,
auto: true,
//autoControls: true
pagerCustom: '#bx-pager'
/*minSlides: 2,
maxSlides: 2,
slideWidth: 170,
slideMargin: 10,
ticker: true,
speed: 7000*/
});
});
});

Why i can't read the text file using javascript and jquery?

This is the code:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://newsxpressmedia.com/files/theme/jquery.newsTicker.js"></script>
<script>$(function() {
var file = "http://newsxpressmedia.com/files/theme/test.txt";
$.get(file, function (txt) {
//var lines = txt.responseText.split("\n");
var lines = txt.split("\n");
$ul = $('<ul class="newsticker" />');
for (var i = 0, len = lines.length; i < len; i++) {
//save(lines[i]); // not sure what this does
$ul.append('<li>' + lines[i] + '</li>');
}
//$ul.appendTo('body').newsTicker({
$ul.appendTo('div.wcustomhtml').newsTicker({
row_height: 48,
max_rows: 2,
speed: 6000,
direction: 'up',
duration: 1000,
autostart: 1,
pauseOnHover: 1
});
});
});
autostart: 1,
pauseOnHover: 0
});
</script>
The links exist and not give 404 not found.
But i don't see the lines from the text file being reading.
I clicked on my site Ctrl+Shist+C in the Audits tab i see one error:
Unexpected token: test.html:120 i click on it and there is one empty line thats it.
And i'm not using and dont have any file called test.html
The goal is that the jquery will read each time one or two lines and scroll it up.
This is the site:
http://newsxpressmedia.com/test.html
Your javascript code is malformed. Remove this from your javascript:
autostart: 1,
pauseOnHover: 0
});
You should remove this obsolete code from the end of your function:
});
autostart: 1,
pauseOnHover: 0
See jsfiddle

Global JS var not being seen

My company bought a timeline plugin and it throws an error in every browser. It still works in Chrome and FireFox but is totally busted in IE (v11)
The JS error has to do with a global variable (defined in audio.min.js) that is not being seen in a following JS file (jquery.timeline.js).
The JS files in the HTML page are listed with the JS file with the global variable, first, followed by the other JS file, where the error is being generated so that all looks right.
Not sure what could cause this...
<script type="text/javascript" src="/Timeline/js/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/Timeline/js/audiojs/audio.min.js"></script>
<script type="text/javascript" src="/Timeline/js/jquery.timeline.js"></script>
Here is the line that causes the error:
audio.prettyPaused = 0;
The errors:
SCRIPT1028: Expected identifier, string or number
Unable to set property 'prettyPaused' of undefined or null reference
Uncaught TypeError: Cannot set property 'prettyPaused' of undefined
The var "audio" is defined in a separate JS file (audio.min.js), right at the top of the file:
//SHARED VARIABLE TO INTERACT WITH VIDEO & PRETTYPHOTO
var audio;
Here is the line in context:
//HTML5 AUDIO PLAYER
audiojs.events.ready(function() {
var as = audiojs.createAll({
autoplay: true,
loop: true
});
audio.prettyPaused = 0;
});
Even More Context
//jquery.timeline.js
jQuery(document).ready(function() {
jQuery.myTimeline();
});
(function($) {
// GLOBAL VARS
var preload, container, tl, vidRoll, imgRoll, readBt, viewport, images, milestones, content, bar, track, dragger, marksAmount, fadeInDelay;
// CLASS CONSTRUCTOR / INIT FUNCTION
$.myTimeline = function() {
//SETUP VARS
preload = $('.preload');
container = $('#timeline_container');
tl = $('#timeline');
vidRoll = $('.video_rollover');
imgRoll = $('.image_rollover');
readBt = $('.readmore');
viewport = $('#timeline .viewport');
images = $('#timeline .viewport .images');
milestones = $('#timeline .milestones');
content = $('#timeline .milestones .content');
bar = $('#timeline .scrollbar');
track = $('#timeline .scrollbar .track');
dragger = $('#timeline .scrollbar .track .dragger');
marksAmount = $('.marks > div').length;
fadeInDelay = parseInt(tl.attr("data-fadeInDelay"));
//CONFIG ALL ELEMENTS SIZES AND POSITIONS BASED ON HTML ATTRIBS
container.css("width", tl.attr("data-width"));
container.css("height", tl.attr("data-height"));
images.css("width", tl.attr("data-imagesWidth"));
viewport.css("height", tl.attr("data-imagesHeight"));
content.css("width", tl.attr("data-contentWidth"));
milestones.css("height", tl.attr("data-contentHeight"));
bar.css("top", tl.attr("data-imagesHeight") - tl.attr("data-draggerHeight"));
track.css("height", tl.attr("data-draggerHeight"));
dragger.css("height", tl.attr("data-draggerHeight"));
//PRELOAD & GLOBAL FADE IN
preload.delay(fadeInDelay - 500).animate({ opacity:0 }, 500, 'easeOutQuad');
container.delay(fadeInDelay).animate({ opacity:1 }, 1000, 'easeOutQuad');
//HTML5 AUDIO PLAYER
audiojs.events.ready(function() {
var as = audiojs.createAll({
autoplay: true,
loop: true
});
audio.prettyPaused = 0;
});
//PRETTYPHOTO LIGHTBOX GALLERY
$('a[data-rel]').each(function() {
$(this).attr('rel', $(this).data('rel'));
});
$("a[rel^='prettyPhoto']").prettyPhoto({social_tools:false});
//TIPSY - TOOLTIP
readBt.tipsy({ gravity: 'w', fade: true, offset: 5 });
//IMAGE ROLLOVER ICON
imgRoll.append("<span></span>");
imgRoll.hover(function(){
$(this).children("span").stop(true, true).fadeIn(600);
},function(){
$(this).children("span").stop(true, true).fadeOut(200);
});
//VIDEO ROLLOVER ICON
vidRoll.append("<span></span>");
vidRoll.hover(function(){
$(this).children("span").stop(true, true).fadeIn(600);
},function(){
$(this).children("span").stop(true, true).fadeOut(200);
});
//VIDEO THUMB STOPS MUSIC ON CLICK (IF PLAYING)
vidRoll.click(function() {
if (audio.playing) {
audio.prettyPaused = 1;
audio.pause();
} else {
audio.prettyPaused = 0;
}
});
//START DRAG IMAGES FUNCTION
startDrag(images);
//SCROLLBAR MILESTONES MARKS
for ( var i = 0; i < marksAmount; i++ ) {
current = $('#m'+i);
current.stop(true, true)
.delay(fadeInDelay + 500)
.animate({ left:current.attr("data-xpos"), opacity:1 }, 700 + 100*i, 'easeOutQuad')
.show()
.tipsy({ gravity: 's', fade: true, offset: 3, fallback: current.attr("data-label") });
};
//INIT SCROLLBAR
tl.tinyscrollbar({
wheel: 20,
mouseWheel: tl.attr("data-mouseWheel"),
size: tl.attr("data-width"),
draggerWidth: tl.attr("data-draggerWidth")
});
} // END OF CLASS CONSTRUCTOR
var audio; defines it, but doesn't initialize it. That's the problem. Nothing you've shown suggests that audio is actually initialized. My guess would be that audio and audiojs are probably intended to be the same thing, but that's a guess based on just what you provided.
Unable to set property 'prettyPaused' of undefined or null reference means that var audio has not been initialized, so it could be a global problem or just not initialized.
You say it gets created in that script - very well, add code below to make sure:
<script type="text/javascript" src="/Timeline/js/audiojs/audio.min.js">
console.log(audio);
</script>
I would suspect that's going to return "undefined" or "null". Means you have to create the object or request it somehow via that script.

Making a series of photos fade in and out sequentially on a web page using Slick

I would like a series of three images to automatically fade in and out over and over looping on the web page without any user input. Upon suggestion in the comments, I have decided to use the Slick library and have generated the following code:
$('.fade').slick({
accessibility: false,
arrows: false,
draggable: false,
autoplay: true,
autoplaySpeed: 3000,
fade: true,
speed: 1000,
swipe: false,
touchMove: false,
});
It works great for one cycle, and then it completely breaks with images flickering and turning black. Does anyone know how to remedy this?
I was able to use code from this Fiddle to accomplish my goals. All I had to do was slightly rework some of the methods, but this is perfectly what I needed.
http://jsfiddle.net/pdb4kb1a/2/
The JavaScript boils down to:
var imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').className += "fadeOut";
setTimeout(function() {
document.getElementById('slider').src = imgArray[curIndex];
document.getElementById('slider').className = "";
},1000);
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout(slideShow, imgDuration);
}
slideShow();

Categories