The right use of jQuery? Owl carousel - javascript

For my project I use the OwlCarousel. http://www.owlgraphic.com/owlcarousel/#more-demos
I managed to get 3 carousels on my page. But I think the page is getting to slow. Is there a possibility that I make to many steps?
Actually I don't need to read the json file because I store it in the localStorage one page before. But I didn't know how to delete it out without corrupting the code.
So the main question is how to make just one jQuery call to fill all 3 carousels?
This is the code I use to call the carousel:
<div id="dodatni1" style="visibility:hidden" >
<div id="owl-demo" class="owl-carousel" ></div>
</div>
<div id="dodatni2" style="visibility:hidden" >
<div id="owl-demo2" class="owl-carousel" ></div>
</div>
<div id="dodatni3" style="visibility:hidden" >
<div id="owl-demo3" class="owl-carousel" ></div>
</div>
And this is the carousel code:
$(document).ready(function() {
$("#owl-demo").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg ="http://www.spleticna.si/images/"+localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3239){
content += "<a href=\"produkt.html?id=" + j + "&slider=a\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo").html(content);
}
});
$(document).ready(function() {
$("#owl-demo2").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 2615){
content += "<a href=\"produkt.html?id=" + j + "&slider=b\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo2").html(content);
}
});
$(document).ready(function() {
$("#owl-demo3").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});

I'm not sure how much speed you could get but you can rewrite your JS:
$(document).ready(function(){
//Assuming they all use the same data source/settings?
$("#owl-demo3,#owl-demo2,#owl-demo1").owlCarousel({
jsonPath : 'json/fakeData.json',
jsonSuccess : customDataSuccess,
lazyLoad : false
});
function customDataSuccess(data){
var content = "";
var stevec = 0;
var dolzina = parseInt(localStorage.getItem('dolzina'));
for(var j=0;j<dolzina;j++){
if (stevec<10){
var imgg = "http://www.spleticna.si/images/" + localStorage.getItem('imga'+j);
var doza = localStorage.getItem('dozaa'+j);
if (doza == 3140){
content += "<a href=\"produkt.html?id=" + j + "&slider=c\" target='frejm' onclick='pokaziiframe()'><img src=\"" + imgg + "\" onError=this.src='napaka.png'></a>"
stevec=stevec+1;
}
}
}
$("#owl-demo3").html(content);
}
});

Related

How To Parse Blogger Rss feed Using Javascript and get output on a HTML Page?

I want to parse my blogger feed from below RSS Link
https://www.universalmanual.com/feeds/posts/default?alt=rss.
https://www.universalmanual.com/feeds/posts/default/-/[label]?alt=rss
.I want to show that parsed data on a plan HTML Page.
Is there any method to extract it data using javascript.
Usign JSON I will get Title, author name and summary but didn't able to get images, how to add images in below code
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postimage = json.feed.entry[i].media$thumbnail.url;
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var item = '<div class="wrapper"><img src=' + postimage + '><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://www.universalmanual.com/feeds/posts/summary?orderby=published&max-results=500&alt=json-in-script&callback=mycallback"></script>
Why not using blogger JSON feed, It is lightweight compared to XML feed (used in Atom and RSS) You can use ?alt=json parameter to access json feed like this
https://www.universalmanual.com/feeds/posts/default?alt=json
To parse JSON feed using javascript use ?alt=json-in-script
The following example shows the last post title from your blog
<div id="content"></div>
<script>
function get(json) {
document.getElementById('content').innerHTML = "<h2>" + json.feed.entry[0].title.$t + "</h2>";
}
</script>
<script src="https://www.universalmanual.com/feeds/posts/default?alt=json-in-script&callback=get"></script>
To show post image in your code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="https://www.universalmanual.com/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

Javascript DOM manipulation

Hello, is there any way when my script outputs an image can i make it output a bootstrap row instead? I need 3 rows and 4 columns in each:
<div class="row">
<div class="col-md-3">
// IMAGE HERE
</div>
<div class="col-md-3">
// IMAGE HERE
</div>
<div class="col-md-3">
// IMAGE HERE
</div>
</div>
I need there to be 4 rows holding 3 images per row which I am struggling to get my head around. Here is my javascript code so far, if anyone could help it would be appreciated.
function displayContent() {
document.getElementById("findCar").onsubmit = function() {
var registration = document.getElementById("regPlate").value,
reference = document.getElementById("stockRef").value;
var regArray = registration.split(''),
refArray = reference.split(''),
referenceNinth = refArray[10];
var reverseReg = regArray.reverse();
var obfuscated = [];
var obf_index = 0;
for(i=0; i<=6; i++) {
obfuscated[obf_index] = refArray[i];
obf_index++;
obfuscated[obf_index] = reverseReg[i];
obf_index++;
}
obfuscated.push(referenceNinth);
var obfuscatedString = obfuscated.join("");
var camera = [];
var cameraSize = "350";
var cam_index = 0;
for(i=0; i<=1; i++) {
if(i>0) cameraSize = "800";
camera[cam_index++] = cameraSize+"/f";
camera[cam_index++] = cameraSize+"/i";
camera[cam_index++] = cameraSize+"/6";
camera[cam_index++] = cameraSize+"/5";
camera[cam_index++] = cameraSize+"/4";
camera[cam_index++] = cameraSize+"/r";
}
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
document.body.appendChild(img);
}
return false;
};
}
You could build up an html string in your loop and then append using .innerHTML.
e.g. - replace your final for loop with something like:
var newHtml = '<div class="row">';
for (i = 0; i <= 11; i++) {
newHtml = newHtml + '<div class="col-md-3">' +
'<img src = "' +
'http://imagecache.arnoldclark.com/imageserver/' + obfuscatedString + '/' + camera[i] + '"></img>' +
'</div>';
}
newHtml = newHtml + '</div>';
document.getElementById("#IdOfElementToAppendTo").innerHTML = newHtml;

Creating Pages Dynamically

The following is my code where i am updating the content of the dynamically created pages constantly but the problem is my update function is running every 3 seconds on pages that i am not even viewing. i am not able to fix this.
var widgetNames = new Array();
var widgetId = new Array();
$( document ).on( "pagecreate", function() {
$( "body > [data-role='panel']" ).panel().enhanceWithin();
});
$(document).on('pagecreate', '#page1', function() {
$("#log").on('click', function(){
$.ajax({
url: "script.login",
type: "GET",
data: { 'page':'create_user', 'access':'user','username':$("input[name='username']").val(), 'password':$("input[name='password']").val()},
dataType: "text",
success: function (html) {
console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
for(var i =0;i<res.length;i++){
var temp = res[i].split(',');
if(temp.length >= 3){
widgetNames[i] = (temp[2].replace('");','')).replace('"','');
widgetId[i] = temp[1].replace("'","").replace("'","").replace(/ /g,'');
}
}
var AllWidgets = ''
var testwidget = new Array();
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for(var i =0;i<tempWidgetContent.length;i++){
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{')+1);
testwidget[i] = widgetContent.replace("site +","");
}
var widgetPart = new Array();
for(var i = 0; i<widgetNames.length; i++){
var pageHeaderPart = "<div data-role='page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header' data-position='fixed'><a data-iconpos='notext' href='#panel' data-role='button' data-icon='flat-menu'></a><h1>BASKETBALL FANATICO</h1><a data-iconpos='notext' href='#page2' data-role='button' data-icon='home' title='Home'>Home</a></div> <div data-role='content'>";
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
widgetPart[i] = '<DIV style=\" text-align: center; font-size: 100pt;\" id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '$(\"#widgetContainer_'+widgetId[i]+'").html(counterValue);' + '}' + 'setInterval(function(){UpdateWidgetDiv'+widgetId[i]+'()},3000)' + '</SCRIPT>';
AllWidgets +='<a href="#'+widgetId[i]+'" class="widgetLink" data-theme="b" data-role="button" >'+widgetNames[i]+'</a>';
var makePage = $(pageHeaderPart + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
var page = $('body').pagecontainer('getActivePage').prop("id");
console.log('The Page Id is: '+page);
}
});
});
});
In this code i am looking to run the following function
'setInterval(function(){UpdateWidgetDiv'+widgetId[i]+'()},3000)'
only for the page the user is viewing.
Here is a DEMO
When creating the pages, as well as saving the page ids in the widgetId array, I am also saving the current page index as a data attribute on each dynamic page (data-pageindex), and I am assigning a class to all the dynamic pages (dynPageClass):
for (var i = 0; i< 3; i++){
var pageid = 'dynPage' + i;
widgetId.push(pageid);
var p = '<div data-role="page" id="' + pageid + '" data-pageindex="' + i + '" class="dynPageClass">';
p += '<div data-role="header"><h1>Dyn Page' + i + '</h1></div>';
p += '<div role="main" class="ui-content">I am dynamically created</div>';
p += '<div data-role="footer"><h1>Footer</h1></div>';
p += '</div>';
$('body').append($(p));
}
The the swipe code can be handled with one handler on the dynPageClass that handles both swipeleft and swiperight:
$(document).on("swiperight swipeleft", ".dynPageClass", function(e) {
var ind = parseInt($(this).data('pageindex'));
var topageid = "page2";
var rev = true;
if (e.type == 'swiperight'){
if (ind > 0){
topageid = widgetId[ind - 1] ;
}
} else {
rev = false;
if (ind < widgetId.length - 1){
topageid = widgetId[ind + 1] ;
}
}
$.mobile.changePage("#" + topageid, {transition: "slide", reverse: rev});
});
We first get the current page's index from the data attribute and parse it into an integer. Then we see if this is a right or left swipe. If right, and index is greater than 0, we need to go back one dynamic page. Otherwise it is a left swipe and if current page is not the last one, we need to go forward one page.
Your swipeleft code on page2 is left intact:
$(document).on("swipeleft", "#page2", function() {
$.mobile.changePage("#"+widgetId[0], {transition: "slide", reverse: false});
});

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

Categories