generating swipe objects with swipe.js - javascript

Using swipe.js (www.swipejs.com), I'd like to attach it to generated DIVs.
In a Javscript loop, I am doing the following:
$.each( data, function( i, item) {
resultHtml = '<div id="swipe-div-' + item.i + '" class="swipe">' +
'<ul>' +
'<li>Test 1<li>' +
'<li>Test 2<li>' +
'</ul></div>' +
'prev' +
'next';
$('div#results').append( resultHtml );
new Swipe(document.getElementById('swipe-div-' + item.i));
}
: I am having trouble with my prev and next links. I suspect it may have to do with the following line:
new Swipe(document.getElementById('swipe-div-' + item.i));
which is not initializing the swipe object properly.
When I click on prev or next, I get the following error in the Javascript console:
"Uncaught SyntaxError: Unexpected token ILLEGAL"
How can I fix this?

Okay, since nobody has answered this, I figured out how to solve my own problem:
Rather than generating and appending text strings, I just created the structure using document.createElement and appendChild.
At the end of creating the structure, I added in the following code:
var slider = new Swipe(document.getElementById('result-' + item.i));
clickPrev(slider, prev);
clickNext(slider, next);
and added the following functions:
function clickNext(swipeObj, link) {
link.onclick = function () {
swipeObj.next();
return false;
}
}
function clickPrev(swipeObj, link) {
link.onclick = function () {
swipeObj.prev();
return false;
}
}
It was easier to follow this way and works great now.

Related

Unable to alter the css 'background-image' with Jquery

I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.
var changeIt = ""
var backgroundPic = new Array(4);
backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';
var picCounter = 0;
var numberOfPics = 5;
var picTimer;
function setPic(){
alert("hi I want this pic: " + backgroundPic[picCounter]);
$('slider').css('background-image', url + "backgroundPic[picCounter]");
picCounter += 1;
if(picCounter >= numberOfPics){
picCounter = 0;
}
}
$(document).ready(function(){
$('.slider').css('background-image', backgroundPic[picCounter]);
picTimer = setInterval(setPic, 2000);
});
The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:
var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];
var picCounter = 0;
var picTimer;
function setPic() {
// note the . in the jquery object below to indicate a class selector
$('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
picCounter++;
}
$(document).ready(function() {
picTimer = setInterval(setPic, 2000);
setPic();
});
You have to set background image like this:
$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");
You inverted the positioning of the quotemarks on the second line of setPic.
Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);
On your setPic function, this line
$('slider').css('background-image', url + "backgroundPic[picCounter]");
isn't missing a dot on $('.slider')?
You'll need to include double quotes (") before and after the imageUrl like this:
$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');
This way, if the image has spaces it will still be set as a property.

Can't figure out why my JS doesn't work

I've been messing around with JavaScript samples and ever since I edited this one I can't figure out why it wont work. Everything looks fine to me, but here is the code (JSFiddle)
https://jsfiddle.net/en2a8c1v/1/
function click(e) {
document.body.style.backgroundColor='" + e.target.id + "';
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
First, make sure that in the JS settings you have no-wrap enabled (I used no-wrap head) in the load type dropdown.
Next, you need to understand that when you call e.target.id, this is already a string variable. You are literally making the background color "e.target.id". That isn't a color.
Simply change document.body.style.backgroundColor='" + e.target.id + "';
to document.body.style.backgroundColor= e.target.id;
I'm not going to touch on the fact that this is a terrible way to go about this as I am assuming you are just playing with event handling.
Maybe someone will find this usefull. Use CSS attribute: background-color:rgb(x,y,z);
You can do it on simple way, for example:
document.getElementById("elementID").style.backgroundColor = 'rgb('+ this.red + ', ' + this.green + ', ' + this.blue + ')';
These r,g,b values can be, for example:
this.red = 0;
this.green = 255;
this.blue = 130;

AJAX returns previous value in array

I'm making a website to host artwork. The idea is that when the page loads I have JavaScript run a php file that makes a query to the server to get the names and IDs of the image files (artwork.jpg) and display them as thumbnails on a page.
When you scroll over the thumbnail, the artwork is displayed larger on a different part of the screen and the description, specs, etc for the piece of art fades in. My issue is that when I make this second AJAX call it appends the value of the previously moused over image to the screen and does nothing until you've moused over at least two images.
Here's my code for the first ajax call that appends thumbnails to the page and creates a form with the value of the thumnbnail's id:
function getArtDescriptions()
{
$.post('../../path/to/script/get_art.php', function(json)
{
if (json.art.length > 0)
{
$.each(json.art,function()
{
var info =
'<div class = "thumbnail_box">'
+ '<img src = "images/thumbnails/'
+ this['img']
+ '"id = "'
+ this['ID']
+ '"> '
+ '<form id = "art_descriptions'
+ this['ID']
+ '" '
+ 'name = "art_descriptions'
+ this['ID']
+ '">'
+ '<input type = "hidden" id = "descriptions" name = "descriptions" value = "'
+ this['ID']
+ '"></form>'
+ '</div>';
});
}
}, 'json');
}
And this is the code I'm using to make the second AJAX call that is giving me a problem:
setTimeout(function get_id()
{
var tooltipTimeout;
$(".thumbnail_box img").on("mouseenter", function()
{
tooltipTimeout = setTimeout(details(this.id),0);
console.log(this.id);
});
$(".thumbnail_box img").on("mouseleave", function()
{
hideTooltip();
});
function hideTooltip()
{
clearTimeout(tooltipTimeout);
$(".description").fadeOut().remove();
}
}, 800);
//GRAB DESCRIPTIONS FROM DATABASE AND
function details(art)
{
var formname = "#art_descriptions"+art;
var filename = '../../file/path/to/script/get_descriptions.php';
//console.log($(formname).serialize());
$(".thumbnail_box img").on("mouseenter", function()
{
$.post(filename, $(formname).serialize(), function(json)
{
if (json.descriptions.length > 0)
{
//MAKE SURE TO EMPTY OUT DIV CLASSES FOR EACH TAB
$(".description").empty();
$.each(json.descriptions,function()
{
console.log("art method"+this['ID']);
$(".description").append(this['description']+this['ID']).hide().fadeIn("fast");
});
}
}, 'json');
});
};
When I console.log(this['ID']) in the get_id() method the correct value is displayed in the console, but when I console.log("art method"+this['ID'] in the details method I get a value equal to the previously scrolled over thumbnail's ID. I'd really appreciate any insight on this issue.
Is it something to do with the use of setTimeout()? My code would not run without specifying a timeout for the method. For example if I load the page and then scroll over images with ID's 14 and then 13, my console will display:
14
13
art method 14
The issue is that you are appending more of the same events. After the first mouseenter event occurs the details function is called, which then appends another mouseenter event. So subsequent calls will be doing the same thing. You can see an example of this here: http://jsfiddle.net/6qre72fk/.
var counter = 0;
$('#container1').on('mouseenter', function(){
$('#container2').text('First mouseenter');
appendingAnotherMouseEnter();
});
function appendingAnotherMouseEnter(){
$('#container1').on('mouseenter', function(){
$('#container2').text(counter);
counter++;
});
}
You can see how the counter is incremented several times due to all appended the mouseenter events.

call function from inside another Ajax function. works with Pure javascript

I have a quite rare problem, or I don't know since I am a beginner :)
I'm creating a DOM tree with ajax, the output is perfect, except that the functions I'm calling does not work. . If I create the same three with pure JavaScript. it actually calls the function. Well quite hard to explain, will show with some code.
function stickers(){
$(document).ready(function() {
$('#add-new-sticker-btn').click(function() {
$.get('xml/data.xml', function(data) {
$('#page-content-wrapper').empty();
$(data).find('car').each(function() {
var $car = $(this);
var sticker = '<div class="sticker">';
sticker += '<div class ="sticker-drag">' + '</div>';
sticker += '<textarea>' + $car.find('product').text() + '</textarea>';
sticker += '<div class="sticker-close">' + '</div>';
$('#page-content-wrapper').append(sticker);
});
});
return false;
});
});
movewrap(); // <!-- this is the function that I'm trying to call.
}
but If I instead write the pure javascript
function stickers(){
var sticker = createElementWithClass('div', 'sticker'),
textArea = document.createElement('textarea');
var stickerDrag = createElementWithClass('div','sticker-drag')
var stickerClose = createElementWithClass('div','sticker-close')
sticker.appendChild(stickerDrag);
sticker.appendChild(textArea);
sticker.appendChild(stickerClose);
document.getElementById('page-content-wrapper').appendChild(sticker);
movewrap();
} // its calling the moveWrap function.
Any ideas ?
Place the call to moveWrap at the end of your AJAX callback. Currently it's being called after the request is made, not after the response is received, and there won't be anything for it to do because the DOM elements aren't there yet.

jQuery - removing an alert stop code from working

The code below works, but there is an issue with it.
That issue is that unless the alert(this.href); - (about line 11) is in the code the following function does not work.
//There are pages which make up 2 chapters in this content
//We shall attempt to grab all the links from these pages
var c;
var chapters = new Array();
chapters[0] = "original/html/0/ID0EFJAE.html";
//Loop through each page of links
$.each(chapters, function(key, value) {
$("#theContent").append("<div class='chapterindex" + key + "'>working</div>");
$(".chapterindex" + key).load(value + " .content");
alert(this.href);
$(".chapterindex" + key + " div.link a").each(function(intIndex) {
alert(".chapterindex" + key);
});
});
If I take the first alert out of line 11 then the last alert doesn't fire. What am I doing wrong?
The delay that the alert is causing is allowing the data in your load call to load. I suspect that when you remove the alert the data does not load in time.
Try using a callback with your load call, something like (code not tested) -
$(".chapterindex" + key).load(value + " .content",function () {
$(".chapterindex" + key + " div.link a").each(function(intIndex) {
alert(".chapterindex" + key);
});
});
The first alert is probably giving the load function enough time to finish so when you take it out the load function is not done when its trying to fire your second alert.

Categories

Resources