UPDATE: JavaScript code is displaying as child node - javascript

SOLUTION: I figured it out. I used jQuery instead of JavaScript with a little help from zohodiscussions.com.
Ajax Google plugin: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
**js. file:**
function form_input_classes() {
jQuery('input[type="text"]').addClass('text');
jQuery('input[type="password"]').addClass('text');
jQuery('input[type="checkbox"]').addClass('checkbox');
jQuery('input[type="radio"]').addClass('radiobutton');
jQuery('input[type="submit"]').addClass('submit');
jQuery('input[type="image"]').addClass('buttonImage');
}
function form_labelize() { jQuery(".labelize input:text").clearingInput(); }
var version = jQuery.browser.version;
if (version instanceof Object) { version = version.number(); }
function loadXMLDoc(XMLname) {
return jQuery.ajax({ async: false, url: XMLname }).responseXML;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
jQuery(function () {
jQuery('script').remove()
form_input_classes();
form_labelize();
var pauseClicked = function () {
jQuery('#cycle').cycle('pause');
jQuery('#play').attr("style", "display:block");
jQuery('#pause').attr("style", "display:none");
jQuery('#pause').removeClass("active");
return false;
};
var playClicked = function () {
jQuery('#cycle').cycle('resume');
jQuery('#pause').attr("style", "display:block");
jQuery('#play').attr("style", "display:none");
jQuery('#pause').addClass("active");
return false;
};
jQuery('#play').attr("style", "display:none");
jQuery('#pause').attr("style", "display:block");
jQuery('#pause').click(pauseClicked);
jQuery('#play').click(playClicked);
jQuery("#slideNavigation a").focus(function () {
jQuery(this).blur();
});
jQuery('#cycle').cycle({
fx: 'fade',
speed: 1000,
timeout: 5000,
prev: '#prev',
next: '#next',
pager: '#hero-nav ul ',
pagerAnchorBuilder: function (idx, slide) {
return '#hero-nav li:eq(' + idx + ') a.page';
}
});
})
**HTML references:**
<div id="content" class="clearfix home">
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
jQuery(M).find('image').each(function (i, img) {
document.write("<img src='" + jQuery(img).text() + "' />");
})
</script>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
jQuery(M).each(function (i, item){
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
document.write("<a href='" +
jQuery(item).find('filePath').text() + "' target='_blank'>" +
jQuery(item).find('description').text()
+ "</a>");
document.write("</div>")
document.write("<a class='page' href='#'></a></li>")
})
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom"/></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom"/>
</a>
</div>
<!--<div id="slideNavigation"></div>-->
</div>
<!-- /#hero-nav -->
</div>
<!-- /#hero-cycle -->
</div>
<!-- /#hero -->
</div>
I updated my code and the rotating images are inline with the description. The only problem I have is the javascript loads first in place of a 1st image. There are only 3 images and the code displays firs then image #1 and so on. Is this a browser issue with ActiveXObject and IE 9? I'm having a similar issue with FireFox latest version. Nothing shows in this browser. Any help? –
.html file:
<head><script type="text/javascript">
<!--
function loadXMLDoc(XMLname)
//
{
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc = new window.XMLHttpRequest();
xmlDoc.open("GET", XMLname, false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
//-->
</script>
</head>
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
for (i = 0; i < M.length; i++) {
document.write("<img src='" + xmlDoc.getElementsByTagName("image")[i].childNodes[0].nodeValue + "' />");
}
</script>
</div>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
for (i = 0; i < x.length; i++) { // Start 3 Rotating Images
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
var linkValue = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var linkValue = x[i].getElementsByTagName("filePath")[0].childNodes[0].nodeValue;
document.write("<a href='" + linkValue + "' target='_blank'>");
linkValue = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
document.write(linkValue);
document.write("</a>");
// End description for Rotating Images
document.write("</div>");
document.write("<a class='page' href='#'></a></li>");
}
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom" /></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom" />
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div>
XML file:
`<?xml version="1.0" encoding="utf-8"?>
<homepage>
<rotatingImages>
<item>
<image>manage/newImages/soldier-sunset.jpg</image>
<description>My Test 1</description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
<item>
<image>manage/newImages/2012-04-03-jet.jpg</image>
<description>My Test3</description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
<item>
<image>manage/newImages/sigar-brochre.jpg</image>
<description>My Test2 </description>
<filePath>http://www.sigar.mil/newsroom/spotlight/12/2012-sep-05-sopko-visits-afghanistan.html </filePath>
</item>
</rotatingImages>
</homepage>`

Since rotator and cycle elements are added dynamically, they don't exist when the page loads and the jQuery function runs. You need to delegate with .on() so that the handlers will be added when the elements are. For information on .on, see http://api.jquery.com/on/ and scroll down to the section on Direct and delegated events.
Another problem with your page is that you use the same ID each time through the for-loop. IDs have to be unique. The repeated IDs are coming from this code:
for (i = 0; i < x.length; i++) {
document.write("<div id='rotator'><div id='cycle' class='clearfix'><div class='entry clearfix'>");
Each time through the loop it adds DIVs with IDs 'rotator', 'cycle', 'hero-cycle', and 'hero-nav'.

Put the jQuery('#cycle').cycle({ … }); code into the jQuery(document).ready function.

**SOLUTION:** I figured it out. I used jQuery instead of JavaScript with a little help from zohodiscussions.com.
Ajax Google plugin: http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js
**js. file:**
function form_input_classes() {
jQuery('input[type="text"]').addClass('text');
jQuery('input[type="password"]').addClass('text');
jQuery('input[type="checkbox"]').addClass('checkbox');
jQuery('input[type="radio"]').addClass('radiobutton');
jQuery('input[type="submit"]').addClass('submit');
jQuery('input[type="image"]').addClass('buttonImage');
}
function form_labelize() { jQuery(".labelize input:text").clearingInput(); }
var version = jQuery.browser.version;
if (version instanceof Object) { version = version.number(); }
function loadXMLDoc(XMLname) {
return jQuery.ajax({ async: false, url: XMLname }).responseXML;
}
xmlDoc = loadXMLDoc("demo.xml");
var M = xmlDoc.getElementsByTagName("rotatingImages");
jQuery(function () {
jQuery('script').remove()
form_input_classes();
form_labelize();
var pauseClicked = function () {
jQuery('#cycle').cycle('pause');
jQuery('#play').attr("style", "display:block");
jQuery('#pause').attr("style", "display:none");
jQuery('#pause').removeClass("active");
return false;
};
var playClicked = function () {
jQuery('#cycle').cycle('resume');
jQuery('#pause').attr("style", "display:block");
jQuery('#play').attr("style", "display:none");
jQuery('#pause').addClass("active");
return false;
};
jQuery('#play').attr("style", "display:none");
jQuery('#pause').attr("style", "display:block");
jQuery('#pause').click(pauseClicked);
jQuery('#play').click(playClicked);
jQuery("#slideNavigation a").focus(function () {
jQuery(this).blur();
});
jQuery('#cycle').cycle({
fx: 'fade',
speed: 1000,
timeout: 5000,
prev: '#prev',
next: '#next',
pager: '#hero-nav ul ',
pagerAnchorBuilder: function (idx, slide) {
return '#hero-nav li:eq(' + idx + ') a.page';
}
});
})
**HTML references:**
<div id="content" class="clearfix home">
<div id="hero">
<div id='rotator'>
<div id='cycle' class='clearfix'>
<script type="text/javascript">
jQuery(M).find('image').each(function (i, img) {
document.write("<img src='" + jQuery(img).text() + "' />");
})
</script>
</div>
</div>
<!--end-rotating-images-->
<div id="hero-cycle" class="clearfix">
<div id="hero-nav">
<ul>
<script type="text/javascript">
jQuery(M).each(function (i, item){
document.write("<li class='hero-text'>");
document.write("<div class='hero-info clearfix'>");
document.write("<a href='" +
jQuery(item).find('filePath').text() + "' target='_blank'>" +
jQuery(item).find('description').text()
+ "</a>");
document.write("</div>")
document.write("<a class='page' href='#'></a></li>")
})
</script>
</ul>
<div id="annc_controls">
<a href="#" id="play">
<img src="images/blue_play.gif" alt="Play" border="0" style="vertical-align: text-bottom"/></a>
<a href="#" id="pause">
<img src="images/blue_pause.gif" alt="Stop" border="0" style="vertical-align: text-bottom"/>
</a>
</div>
<!--<div id="slideNavigation"></div>-->
</div>
<!-- /#hero-nav -->
</div>
<!-- /#hero-cycle -->
</div>
<!-- /#hero -->
</div>

Related

Pass folder name via URL to SPO Rest API call in Custom ASPX page

I have one page listing different folder URLs. Clicking the link should trigger the code below on the second page using parameters passed from the URL from page one.
I am trying to pass Folder name parameter via URL to load the API call in custom ASPX page on SPO. The URL linking to this second page code below will have the folder details.
URL format from page one - <<<SPO_SITE>>>/teams/<<<SPO_TENANT>>>/SiteAssets/Image.aspx?Folder="<<<FOLDER_NAME>>>"
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/jquery-3.5.1.min.js"></script>
<script>
$(function(){
var requestUri = "<<<SPO_SITE>>>/teams/<<<SPO_TENANT>>>/_api/web/getfolderbyserverrelativeurl('<<<SPO_DOC_LIB>>>/<<<FOLDER>>>')/Files?$top=2000&$select=ServerRelativeUrl";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var divContent = '<div class="row" id="myList">';
for (var i = 0; i < objItems.length; i++) {
divContent += '<div class="col-md-3"><div class="card mb-4 shadow-sm"><img src="<<<SPO_SITE>>>/' + objItems[i].ServerRelativeUrl + '"><a class="stretched-link" target="_blank" href="<<<SPO_SITE>>>/' + objItems[i].ServerRelativeUrl + '"></a></div></div>';
}
$('#ImgGrid').append(divContent);
}
});
</script>
<main role="main">
<section class="pt-4 pb-4 text-center">
<div class="container">
</div>
</section>
<div class="container">
<div id="myList">
<div id="ImgGrid"></div>
</div>
</div>
</main>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
Kindly review the code and advice.
If the images is in the url like this:
https://Tenantname.sharepoint.com/sites/sitename/SPO_DOC_LIB/FOLDER
Then in getfolderbyserverrelativeurl please pass the relative url like this:
/_api/web/getfolderbyserverrelativeurl('/sites/sitename/<<<SPO_DOC_LIB>>>/<<>>')/Files?$top=2000&$select=ServerRelativeUrl
Update with completed code snippet:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.6.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
$(function () {
var relativeurl = "/sites/dev/Share Documents/" + GetParameterValues("Folder");
var requestUri = _spPageContextInfo.webAbsoluteUrl +"/_api/web/getfolderbyserverrelativeurl('"+relativeurl+"')/Files?$top=2000&$select=ServerRelativeUrl";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
});
});
function onSuccess(data) {
var objItems = data.d.results;
console.log(objItems);
var divContent = '<div class="row" id="myList">';
for (var i = 0; i < objItems.length; i++) {
divContent += '<div class="col-md-3"><div class="card mb-4 shadow-sm"><img src="' + objItems[i].ServerRelativeUrl + '"><a class="stretched-link" target="_blank" href="' + objItems[i].ServerRelativeUrl + '"></a></div></div>';
}
$('#ImgGrid').append(divContent);
}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
</script>
<main role="main">
<section class="pt-4 pb-4 text-center">
<div class="container">
</div>
</section>
<div class="container">
<div id="myList">
<div id="ImgGrid"></div>
</div>
</div>
In the code demo above, My site url is https://tenant.sharepoint.com/sites/dev/
So the relative url is using /sites/dev/Shared Documents/folder1
Update:
Get Folder querystring parameter in the url like this in the second page:
JSRequest.EnsureSetup();
var itemId = JSRequest.QueryString["Folder"];

How to add and remove from array?

I have a series of images and I want to insert their src values and then add some div elements too associated with it into the array into the array on a click on the image and remove them if we click again.
Trying the following but I got the logic wrong as it is not removing the already el:
HTML
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
JS
$('body').on('click', '.card img', function () {
var urls = [];
if($(this).hasClass("checked")) {
$(this).removeClass("checked");
var urlInArray = $(this).attr('src');
urls.splice($.inArray(urlInArray, urls), 1);
console.log(urls);
} else {
$(this).addClass("checked");
var checkedItems = $('.checked'); // get the checked items
checkedItems.each(function () {
urls.push($(this).attr('src'));
});
var str = '';
urls.forEach(function (url) {
str += '<div class="card"><img class="img-fluid" onerror="this.parentNode.removeChild(this);" src="' + url + '"></div>';
});
console.log(urls);
}
});
You can use splice() to remove url from array and indexOf() to get index of that url.
var urls = [];
$(".card img").click(function() {
var src = $(this).attr('src')
$(this).hasClass('checked') ? urls.splice(urls.indexOf(src), 1) : urls.push(src);
$(this).toggleClass('checked')
console.log(urls)
})
.checked {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="test_1.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
That's an overkill of bytes. Use simple indexOf to check if image is already in urls. I don't see how checked on img tag is semantic, perhaps switch to data-checked?
var urls = [];
$('body').on('click', '.card img', function () {
// src; unique
var src = $(this).attr('src'),
// index of src key
index = urls.indexOf(src);
// if element exists;
if(index >= 0){
// remove
urls.splice(index, 1);
} else {
// add to urls
urls.push(src);
}
console.log(urls);
});
div {
display:inline-block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="card">
<img src="https://source.unsplash.com/uK9QFr3fFk0/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/pHANr-CpbYM/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/39-0VXkvcbw/100x100">
</div>
It should be very simple. check this
$(document).ready(function () {
var status = {};
$('body').on('click', '.card img', function () {
var src = $(this).attr('src');
if (typeof status[src] == 'undefined' || status[src] == false) {
status[src] = true;
$(this).next().html('added');
} else {
status[src] = false;
$(this).next().html('removed');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="france_fan.jpg" alt='image_1'>
<span>removed</span>
</div>
<div class="card">
<img src="italy-s.gif" alt='image2'>
<span>removed</span>
</div>
<div class="card">
<img src="bangladesh-s.gif" alt='image3'>
<span>removed</span>
</div>

Can not display same page twice in jquery mobile cordova phonegap

Confused why this happened,
when I am in second page (ex: product_detail.html?id=1), then I want to click the same page but different id (ex :product_detail.html?id=5) it is not working, nothing displayed.
Here is my index.html
<script type="text/javascript" src="cordova.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.mobile.min.js"></script>
<div class="item">
<img src="http://web/banner2.jpg">
</div>
<div class="item">
<img src="http://web/banner3.jpg">
</div>
<script>
$( document ).on( "pageinit", "#detailsPage", function( event ) {
var parameters = $(this).data("url").split("?")[1];
parameter = parameters.replace("id=","");
var devid=localStorage.getItem("macid");
$.getJSON('http://url_web_services/related_product.php?id='+parameter, product_detail);
});
function product_detail(data) {
var employee = data.item;
var urls="";
urls="http://url_web_services/"+employee.product_image;
var myid3="";
myid3 = localStorage.getItem("macid");
$('#product_detail').append('<a href="product_detail.html?id='+employee.product_id+'"><div class="item">');
$('#product_detail').append('<div class="xxw"><img src="http://webservice' + employee.promo_image +'"></div>');
$('#product_detail').append('<div style="background-color:#2E64FE;margin-top:15px;"><font color="#FFFFFF" face="arial" size="3">' + employee.product_name + '</font></div><br>');
$('#product_detail').append('</div></a>');
//SIMILAR PRODUCT
var idp=employee.promo_id;
$.getJSON('http://webservice/product_related.php?id='+idp, function(data) {
employees2 = data.items;
$.each(employees2, function(index, employee2) {
$('#product_similar').append('<a href="product_detail.html?id='+employee2.product_id+'"><div class="some">'+
'<div><img src="http://webservice/' + employee2.product_image +'" class="bgr"></div>'+
'<div class="four"><p style="margin-left:5px;margin-top:2px;"><font face="arial" size="2" color="black"><b>'+employee2.product_name+' ....</b></font></p></div>'+
'</div></a>');
});
});
}
</script>
here is my second page product_detail.html
<div data-role="page" id="detailsPage">
<div data-role="header" data-tap-toggle="false" data-theme='b'>
<h1 class="header-title">Detail</h1>
</div>
<div data-role="content" id="product_detail">
</div>
<br>
<div style="background-color:#3104B4;margin-top:5px;"><font color="#FFFFFF" face="arial" size="3"><center>PRODUCT SIMILAR</center></font></div>
<div id="product_similar" style="background-color:#E6E6E6;margin-top:2px;">
</div>
<div data-role="footer" data-theme="none" data-inner="true" data-border="false">
</div>
</div>
when I click one of item in product_similiar (it means reload the same page, but different ID, it displays nothing)
You can try dynamically creating page with the new values, here is an example:
<img src="http://web/banner2.jpg">
<script>
function create_page(page_id) {
var jsonUrl = 'http://url_web_services/related_product.php?id=' + page_id
var content = $('#detailsPage').html();
var newPage = '<div data-role="page" id="product_detail_id=' + page_id + '">' + content + '</div>'
$('body').append(newPage);
//initialize the new page
$.mobile.initializePage();
//navigate to the new page
$.mobile.changePage("#product_detail_id=" + page_id, "pop", false, true);
//now you can get #product_detail
$.getJSON(jsonUrl , product_detail);
}
</script>
With some adjustments it should work

Am I using the jQuery .each function incorrectly?

I am using some jQuery to retrieve and parse some JSON from a third party website, so I can use images from that site to populate a gallery.
Please see the details below, and reproduced in this JSFiddle:
$(document).ready(function() {
function populateImages(path) {
$('.crush').each(function() {
$(this).html('<img src="' + path + '/>');
});
}
$.ajax({
url: 'http://tubecrush.net/wp_api/v1/posts?callback=show',
dataType: "jsonp",
type: "get",
success: function(data) {
var regex = /"/g;
var i = 0;
for (i = 0; i < 20; i++) {
var content = data.posts[i].content_display;
var part1 = content.split('src="');
var part2 = part1[1].split(regex);
var imgPath = part2[0];
console.log(imgPath);
populateImages(imgPath);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1>Result:</h1>
<div id="result">
<div class="pure-g">
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
<div class="crush"></div>
</div>
</div>
I know the part that's retrieving the JSON query is working because it is outputting the image path I want to grab in the console. However, the last part is using the jQuery .each function to add an tag and fill it with the path I have retrieved with the AJAX, but it's not working.
Not sure what I am doing wrong.
Please note that although the second part is in its own function called populateImages, I have tried embedding that code in the loop part, and still had the same effect.
Greatly appreciated if anyone can help.
You shouldn't use each for that, it only means that you will put an image in every element for the first URL, then replace all of them with an image for the second URL and so on. You can make the populateImages function take a index where you want to place the image. Use the eq method to get a specific element:
function populateImages(index, path) {
$('.crush').eq(index).html('<img src="' + path + '"/>');
}
Call the function with the loop counter as index:
populateImages(i, imgPath);
You can easily narrow down your selection with jQuery's eq().
http://jsfiddle.net/BramVanroy/rzg64bvh/6/
$(document).ready(function () {
$.ajax({
url: 'http://tubecrush.net/wp_api/v1/posts?callback=show',
dataType: "jsonp",
type: "get",
success: function (data) {
var regex = /"/g;
var i = 0;
for (i = 0; i < 20; i++) {
var content = data.posts[i].content_display;
var part1 = content.split('src="');
var part2 = part1[1].split(regex);
var imgPath = part2[0];
console.log(imgPath);
$('.crush').eq(i).html('<img src="' + imgPath + '">');
}
}
});
});
Everytime the loop does an iteration, you are populating every .crush with the same image. This should work:
$(document).ready(function(){
var crushes = $('.crush');
$.ajax({
url:'http://tubecrush.net/wp_api/v1/posts?callback=show',
dataType:"jsonp",
type:"get",
success:function(data){
var regex = /"/g;
var i = 0, l = crushes.length;
for(i=0;i<l;i++) {
var content = data.posts[i].content_display;
var part1 = content.split('src="');
var part2 = part1[1].split(regex);
var imgPath = part2[0];
console.log(imgPath);
crushes.eq(i).html('<img src="' + imgPath + '"/>');
}
}
});
});

javascript draggable script tracking position

I am following this guide: http://draggabilly.desandro.com/
which I think is hard to understand and I can't seem to figure out what to add to track the positions of the elements I drag around. If you look on the site, you can see the last example where they do it. My example so far is this:
<div id="house_wall1">
<img src="xxx" class="draggie" style="position:relative;">
<img src="xxx" class="draggie" style="position:relative;">
<img src="xxx" class="draggie" style="position:relative;">
<!--Cypyrights and many thanks to http://desandro.mit-license.org for element movements -->
<?php if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
<?php
echo $username;
?>
</div>
<script type="text/javascript" src="draggabilly.pkgd.min.js"></script>
<script>
( function() {
var container = document.querySelector('#house_wall1');
var elems = container.querySelectorAll('.draggie');
for ( var i=0, len = elems.length; i < len; i++ ) {
var elem = elems[i];
new Draggabilly( elem, {
containment: true
});
}
})();
function onDragMove( instance, event, pointer ) {
console.log( 'dragMove on ' + event.type +
pointer.pageX + ', ' + pointer.pageY +
' position at ' + instance.position.x + ', ' + instance.position.y );
}
// bind event listener
draggie.on( 'dragMove', onDragMove );
// un-bind event listener
draggie.off( 'dragMove', onDragMove );
// return true to trigger an event listener just once
draggie.once( 'dragMove', function() {
console.log('Draggabilly did move, just once');
});
This script makes it possible to move the images around but it does not track their positions yet even though I have tried adding it at the bottom of the script as you can see. Does anybody have an idea what can be wrong or whats needed? I'm fairly new at Jquery, Javascript. Many thanks.
Change your code to this, Works fine for me. You just need to use offset() methods to get the position of dragged element when it is getting dragged and position() method to get the co ordinates of the position where it got dropped.
HTML:
//include these files.
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src=" http://code.jquery.com/jquery-2.0.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<body>
<div id="container">
<img id="productid_1" src="Lionel Messi New Wallpaper 2012 07.jpg" class="item" alt="" title="" height="100px" width="100px"/>
<img id="productid_2" src="bienvenidos_a_uniformes_deportivos_monterrey_4_216235520.jpg" class="item" alt="" title="" height="100px" width="100px" />
<img id="productid_3" src="lionel-messi-wallpapers-hd.jpg" class="item" alt="" title="" height="100px" width="100px"/>
<?php if (login_check($mysqli) == true) : ?>
<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
<?php
echo $username;
?>
</div>
<div id="start">Waiting for dragging the image get started...</div>
<div id="stop">Waiting image getting dropped...</div>
<ul>
<li id="posX"></li>
<li id="posY"></li>
</ul>
</body>
JQUERY:
<script>
$(document).ready(function(){
$(".item").draggable({
drag: function(){
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
},
// Find original position of dragged image.
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).position();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
},
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
</script>
EDIT:
$(document).ready(function(){
$(".item").draggable({
containment: '#limit_div',
drag:function(){......
//where #limit_div will be parent div of the #container div.

Categories

Resources