I can't get id of a image in javascript - javascript

I want to get the id of my img in javascript on a mousewheel but when I do a getElementById I it tells me that the length is null
this is the function where I put my img
function parse_data(data)
{
var json = data;
var obj = JSON.parse(json);
var buff = "";
for(var i in obj)
{
//document.write('<br>' + i + '<br>');
for (var j in obj[i])
{
if (obj[i][j] == true)
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
else
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
}
buff += "<br>";
}
document.getElementById('frisekk').innerHTML = buff;
}
And this is the function where I want to get back the id of an img on mousewheel
function test()
{
var obj = document.getElementById('img');
alert(obj.length); //obj.length is null...
if (event.wheelDelta >= 120)
unit -= 60;
else
unit += 60;
request(readData);
}
how could I get the id of my img ?
there is all the html code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script>
var unit = 60;
var date = 'Mon Oct 20 2014 19:25:00 GMT (CET)';
function request(callback)
{
var xhr = getXMLHttpRequest();
var frise = 600;
var template = 'lab';
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
callback(xhr.responseText);
};
xhr.open("GET", "a.php?Frise=" + frise + "&Unit=" + unit + "&Template=" + template + "&Date=" + date, true);
xhr.send(null);
}
function readData(sData)
{
parse_data(sData);
}
function parse_data(data)
{
var json = data;
var obj = JSON.parse(json);
var buff = "";
for(var i in obj)
{
//document.write('<br>' + i + '<br>');
for (var j in obj[i])
{
//document.write(j + "=" + obj[i][j] + '<br>');
if (obj[i][j] == true)
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_green.jpg\" border=\"0\" /></a>";
else
buff += "<a href=\"#\" onmousewheel=\"test()\" ><img id=\"obj[i]\" src=\"../images/pix_gray.jpg\" border=\"0\" /></a>";
}
buff += "<br>";
}
document.getElementById('frisekk').innerHTML = buff;
}
function test()
{
var obj = document.getElementById('img');
alert(obj.length);
if (event.wheelDelta >= 120)
unit -= 60;
else
unit += 60;
request(readData);
}
</script>
<script>
function getXMLHttpRequest()
{
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
xhr = new XMLHttpRequest();
}
}
else
{
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
</script>
<span id="frisekk"> <br/> </span>
</head>
<body>
<form>
<p>
<input type="button" onclick="request(readData);" value="Exécuter" />
</p>
</form>
</body>
</html>

document.getElementById does not get the id for you, it gets the element by id passed. Since you didn't post your HTML I can't really say whether your <img /> tag has the id of img, but I'm assuming not. What you are looking for is document.getElementsByTagName('img') to get tevery img element on the page and then use a loop to find which one you need (or add [0] if you know you only have one to select the first element).
So you have two options:
Add an ID to your element (best option)
<img src="path/to/image.jpg" id="my_image" />
var finalElement = document.getElementById("my_image");
Find all elements with the tagname 'img' and then search through them for the right on
<img src="path/to/image.jpg" />
var elements = document.getElementsByTagName("img");
var finalElement = false;
for(var i = elements.length -1; i >= 0; i--){
// match your element and return
if(/* criteria */){
finalElement = elements[i];
break;
}
}
Have only one image on your page and select that:
<img src="path/to/image.jpg" id="my_image" />
var finalElement = document.getElementsByTagName("img")[0];
Update
Your onmousewheel property could be supported, but then you need to do it slightly differently, because your link has the onmousewheel event.
<!-- add the 'this' keyword to your test() function to pass the <a> element -->
<img src="path/to/image.jpg" />
With this structure (one <img> nested in an <a>), you can pass the <a> to the function using the thiskeyword.
/* Add a variable to receive your <a> in your test() function. */
function test(link){
/* Use childNodes[0] to select the first child element of the a. */
var image = link.childNodes[0];
/* Will alert '1' if the <a> has a child, will alert '0' if the <a> is empty.*/
alert(image.length);
}
Now you can easily access the only child of the a element, the image, and do something with that.
I am not sure whether onmousehweel is supported on an element, so pelase consider an onclick or onmouseover to test this function. If you decide to test with onmouseover, use the console.log to log instead of alert, otherwise you'll drown in alerts.

Can't you parse the id in the function call?
Eg in:
onmousewheel=test(obj[i])
and in the function,
function test(id)??

Related

javascript get natural width/height of all images in table

I am trying to get the actual image sizes from the images listed in column Image and display it in column Image Size.
The problem I have is that I am only able to get the size of the first image, which is added in each cell for column Image Size.
jsFiddle: https://jsfiddle.net/a92ck0em/
var xmlFile = 'https://raw.githubusercontent.com/joenbergen/files/master/XMLParse2.xml';
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", xmlFile, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
xmlFunction(this.response);
}
};
}
function xmlFunction(xml) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
var table = "<tr><th>Category</th><th>Title</th><th>Image</th><th>Image Size</th></tr>";
var x = xmlDoc.getElementsByTagName("ITEM");
for (var elem of x) {
var titles = elem.getElementsByTagName(
"TITLE")[0].childNodes[0].nodeValue;
var cats = elem.getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue;
var imageURL = elem.getElementsByTagName("IMAGE").length === 0 ? "..." : elem.getElementsByTagName("IMAGE")[0].getAttribute('url');
var imageSize = elem.getElementsByTagName("IMAGE").length === 0 ? "..." : elem.getElementsByTagName("IMAGE")[0].width + 'x' + [0].height;
table += "<tr><td>" + cats + "</td><td>" + titles + "</td><td>" + "<img src=" + imageURL + ' height="150" width="100">' + '</td><td id="cellId"><textTag>' + "" + "</textTag></td></tr>";
}
document.getElementById("myTable").innerHTML = table;
document.querySelector("img").addEventListener('load', function() {
var imgTags = document.querySelectorAll('img'), i;
for (i = 0; i < imgTags.length; ++i) {
var image_width = document.querySelector("img").naturalWidth;
var image_height = document.querySelector("img").naturalHeight;
}
$('#myTable textTag').each(function() {
$(this).append(image_width + 'x' + image_height);
//console.log(image_width + 'x' + image_height);
});
});
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<button type="button" onclick="loadDoc()">Load</button>
<br><br>
<table id="myTable"></table>
Expected:
Ok there are many parts to your question, I started doing the simplest thing, logging that parsed xml document, looks like this:
...
<IMAGE url="...."></IMAGE>
<IMAGESIZE></IMAGESIZE>
...
So in your script you are getting an attribute that does not exist. So you can safely remove this line:
var imageSize = elem.getElementsByTagName("IMAGE").length === 0 ? "..." : elem.getElementsByTagName("IMAGE")[0].width + 'x' + [0].height;
Next you need to check if the images are loaded, simplest thing to do:
"<img src=" + imageURL + ' height="150" width="100" onload="this._loaded = true;">' +
this will add a proprietary _loaded property to it.
Next you need to check when the images are loaded and once loaded fire a function, you need a recursive function to do that which does not blow the stack:
var imgTags = document.getElementsByTagName('img');
function isLoaded(){
if(Array.prototype.slice.call(imgTags).some(function(d,i){return !d._loaded})){
setTimeout(isLoaded,4);
} else {
$('#myTable textTag').each(function(i,node) {
node.textContent = imgTags[i].naturalWidth + 'x' + imgTags[i].naturalHeight;
//console.log(image_width + 'x' + image_height);
});
}
};
isLoaded();
I removed the querySelectorAll(img) bit, it is slower compared to getElementsByTagName and does not return a LIVE HTML Collection, returns a NodeList. The loaded function will fire your Jquery thing once it detects all the _loaded properties. The Array.prototype.slice.call is an old school way to convert HTML Collection or NodeList to a regular array, the cool kids you Array.from nowadays, it is up to you. You might also optimize the above function a bit by storing the result of Array.prototype.slice.call... once, I leave that to you. All in all it looks like this:
https://jsfiddle.net/ibowankenobi/h9evc81a/
The problem is that you need to wait for the images to load before querying properties like width or height.
Normally this is done by setting an onload event handler that updates the display of these properties.
Moreover you're making a loop setting two variables and then, outside of the loop, you're assigning all the images the value of the very same variables.
You need to do the querying inside the second loop instead.

Javascript Next and Previous images

Code is supposed to show next image when clicking on next arrow and previous image when clicked on previous arrow. It does not work though. (error occurs while assigning img.src=imgs[this.i]; it says Cannot set property 'src' of null
at collection.next) .
Javascript code :
var arr = new collection(['cake.png', 'image2.png', 'image3.png', 'image1.png']);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById('element')
this.i++;
if (this.i == imgs.length) {
this.i = 0;
}
img.src = imgs[this.i].src;
}
this.prev = function(element) {
var img = document.getElementById('element');
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i].src;
}
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
Not using jquery. I do not have enough experience in js either. Thank you for your time
You had three mistakes:
You referenced the images as img.src = imgs[this.i].src; and you just had an array of strings, not an array of objects with a src property. img.src = imgs[this.i]; is the correct way to get the URL.
You used
var img = document.getElementById('element');
when you should have used
var img = document.getElementById(element);
element is an argument coming from your onclick event. It holds the id of your image that you should be using. "element" is just a string. You try to find an element with id equal to element which doesn't exist.
Edit: You should also use < and > to represent < and >. Otherwise your HTML might get screwed up. More on that here.
var arr = new collection(['http://images.math.cnrs.fr/IMG/png/section8-image.png', 'https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg', "http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"]);
function collection(imgs) {
this.imgs = imgs;
this.i = 0;
this.next = function(element) {
var img = document.getElementById(element);
this.i++;
if (this.i >= imgs.length) {
this.i = 0;
}
img.src = imgs[this.i];
};
this.prev = function(element) {
var img = document.getElementById(element);
this.i--;
if (this.i < 0) {
this.i = imgs.length - 1;
}
img.src = imgs[this.i];
};
this.next("mainImg"); // to initialize with some image
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input type='button' value='<' name='next' onclick="arr.next('mainImg')" />
<img id='mainImg' src="cake.png">
<input type='button' value='>' name='prev' onclick="arr.prev('mainImg')" />
</body>
</html>
This is how I'd personally do it:
var myCollection = new Collection([
"http://images.math.cnrs.fr/IMG/png/section8-image.png",
"https://www.w3.org/MarkUp/Test/xhtml-print/20050519/tests/jpeg444.jpg",
"http://saturnraw.jpl.nasa.gov/multimedia/images/raw/casJPGFullS72/N00183828.jpg"
], "mainImg");
document.getElementById("next_btn").onclick = function() {
myCollection.next();
};
document.getElementById("prev_btn").onclick = function() {
myCollection.prev();
}
function Collection(urls, imgID) {
var imgElem = document.getElementById(imgID);
var index = 0;
this.selectImage = function() {
imgElem.src = urls[index];
};
this.next = function() {
if (++index >= urls.length) {
index = 0;
}
this.selectImage();
};
this.prev = function(element) {
if (--index < 0) {
index = urls.length - 1;
}
this.selectImage();
};
// initialize
this.selectImage();
}
<!DOCTYPE html>
<html>
<head>
<title>photos</title>
<script src="photos.js"></script>
</head>
<body>
<input id="next_btn" type='button' value='<' />
<img id='mainImg'>
<input id="prev_btn" type='button' value='>' />
</body>
</html>
Why sending string into arr.next('mainImg') function ?
your img element always have the same id, only change src.
and document.getElementById(element) is also the same img element.
html: <img id='mainImg' src="cake.png">
js: document.getElementById('mainImg')
consider img element as a container, and id is it's identifiler.
var start_pos = 0;
var img_count = document.getElementsByClassName('icons').length - 1;
var changeImg = function(direction){
pos = start_pos = (direction == "next")? (start_pos == img_count)? 0 : start_pos+1 : (start_pos == 0)? img_count : start_pos-1;
console.log(pos)
}
document.getElementById('left').onclick = function(){ changeImg("previous"); }
document.getElementById('right').onclick = function(){ changeImg("next"); }

New to regex. Adding a whitespace after all closing tags

Totally new to regex. I know how to find all closing tags /<\/.*?>/g, but I need to add a whitespace after all closing tags. This just strips all closing tags: str = str.replace(/<\/.*?>/g, ' ');
*** Added later
OK, this is the entire script. I can't post it here. You can view it on jsfiddle: https://jsfiddle.net/bw6yfc7g/3/ I want it to automatically add a whitespace ONLY when a closing and an openings tags run one after the other. In other words when Underline is posted after Bold the tags should look like this: <b></b> <u></u> however when they are posted inside each other they should look like this: <b><u></u></b> No spaces.
Here is a way to achieve that with DOM:
function textNodesUnder(el){
var n, walk=document.createTreeWalker(el,NodeFilter.SHOW_ELEMENT,null,false);
while(n=walk.nextNode())
{
if (n.nodeName !== "MYELT")
{
ws_node = document.createTextNode(" ");
n.parentNode.insertBefore(ws_node, n.nextSibling);
}
}
return el.firstChild.innerHTML;
}
function addWsNodes(s) {
var doc = document.createDocumentFragment();
var wrapper = document.createElement('myelt');
wrapper.innerHTML = s;
doc.appendChild( wrapper );
return textNodesUnder(doc);
}
var s = "This is a <span>test</span>and another<br>test <span>here</span>.";
console.log(addWsNodes(s));
// => This is a <span>test</span> and another<br> test <span>here</span> .
Here, the HTML string input is enclosed into a fake element with myelt name, then it is added to a document fragment that is passed to the tree walker. There, we only consider element nodes (SHOW_ELEMENT), and insert a whitespace element right after it. You may adjust the text contents (insert a tab, or spaces, or linebreaks).
UPDATE
Your code is already good, you only have to check if you are inserting something at the end of the text. I added extra_ws variable, and assign whitespace to it only if the starting position is the end of existing text. I am adding also a check if we are not at the start of the string:
if (startPos === txta.value.length && startPos > 0) ...
function addTagSel(tag, idelm) {
var tag_type = new Array('<', '>'); // for BBCode tag, replace with: new Array('[', ']');
var txta = document.getElementById('wmd-input');
var start = tag_type[0] + tag + tag_type[1];
var end = tag_type[0] +'/'+ tag + tag_type[1];
var IE = /*#cc_on!#*/false; // this variable is false in all browsers, except IE
var extra_ws = ""; // ADDED
var offst = 0;
if (IE) {
var r = document.selection.createRange();
var tr = txta.createTextRange();
var tr2 = tr.duplicate();
tr2.moveToBookmark(r.getBookmark());
tr.setEndPoint('StartToEnd',tr2);
var tag_seltxt = start + r.text + end;
var the_start = txta.value.replace(/[\r\n]/g,'.').indexOf(r.text.replace(/[\r\n]/g,'.'),tr.text.length);
if (start === txta.value.length && startPos > 0) { // HERE
extra_ws = " "; // UP TO HERE
offst = extra_ws.length;
}
txta.value = txta.value.substring(0, the_start) + extra_ws + tag_seltxt + txta.value.substring(the_start + tag_seltxt.length, txta.value.length); // AND HERE
var pos = txta.value.length - end.length; // Sets location for cursor position
tr.collapse(true);
tr.moveEnd('character', pos + offst); // start position
tr.moveStart('character', pos + offst); // end position
tr.select(); // selects the zone
}
else if (txta.selectionStart || txta.selectionStart == "0") {
var startPos = txta.selectionStart;
var endPos = txta.selectionEnd;
var tag_seltxt = start + txta.value.substring(startPos, endPos) + end;
if (startPos === txta.value.length && startPos > 0) {
extra_ws = " ";
offst = extra_ws.length;
}
txta.value = txta.value.substring(0, startPos) + extra_ws + tag_seltxt + '\u200C' + txta.value.substring(endPos, txta.value.length);
// txta.value = addWsNodes(txta.value);
// Place the cursor between formats in #txta
txta.setSelectionRange((endPos+start.length+offst),(endPos+start.length+offst));
txta.focus();
}
return tag_seltxt;
}
document.getElementById('big').onclick = function() {
var tag_seltxt = addTagSel('big');
return tag_seltxt;
}
document.getElementById('b').onclick = function() {
var tag_seltxt = addTagSel('b');
return tag_seltxt;
}
document.getElementById('i').onclick = function() {
var tag_seltxt = addTagSel('i');
return tag_seltxt;
}
document.getElementById('u').onclick = function() {
var tag_seltxt = addTagSel('u');
return tag_seltxt;
}
document.getElementById('del').onclick = function() {
var tag_seltxt = addTagSel('del');
return tag_seltxt;
};
.edit_button {
display: inline-block;
color: black;
padding: 5px;
}
<a class="edit_button" id="big"> <span class="titleicon"></span> </a>
<a class="edit_button" id="b"> B </a>
<a class="edit_button" id="i"> <i>I</i> </a>
<a class="edit_button" id="u"> <u>U</u> </a>
<a class="edit_button" id="del"> <del>S</del> </a>
<textarea id="wmd-input"></textarea>

Javascript image to div

So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<img src="images/Tulip_small.jpg" alt="Tulips">
<img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips">
<img src="images/Swan_small.jpg" alt="Swan on Lake">
<img src="images/Red_Tulip_small.jpg" alt="Red Tulips">
<img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees">
<img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video">
</div>
Change the class attribute to id or add the id attribute id="html5gallery"
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
EDIT:
Try this to append image
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!
If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: DEMO
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>

Auto refresh a div containing Twitter posts

I am working with Twitter APIv1.1 and currently I am trying to implement a box which will display my latest tweets. This can be seen here:
http://www.jdiadt.com/twitterv1_1feed/testindex.html
However I would like to make this so that when I tweet, the box is automatically updated. I am quite new to JQuery and Javascript so I would appreciate any advice on how I can do this. I've hear AJAX can be used for something like this. Currently I have to refresh the entire page to display any new tweets. I'd like to only refresh the box.
Here is my script: twitterfeed.js
$(document).ready(function () {
var displaylimit = 10;
var twitterprofile = "jackcoldrick";
var screenname = "Jack Coldrick";
var showdirecttweets = false;
var showretweets = true;
var showtweetlinks = true;
var showprofilepic = true;
var headerHTML = '';
var loadingHTML = '';
headerHTML += '<a href="https://twitter.com/" ><img src="http://www.jdiadt.com/twitterv1_1feed/twitteroauth/images/birdlight.png" width="34" style="float:left;padding:3px 12px 0px 6px" alt="twitter bird" /></a>';
headerHTML += '<h1>'+screenname+' <span style="font-size:13px"><a href="https://twitter.com/'+twitterprofile+'" >#'+twitterprofile+'</a></span></h1>';
loadingHTML += '<div id="loading-container"><img src="http://www.jdiadt.com/twitterv1_1feed/twitteroauth/images/ajax-loader.gif" width="32" height="32" alt="tweet loader" /></div>';
$('#twitter-feed').html(headerHTML + loadingHTML);
$.getJSON('http://www.jdiadt.com/twitterv1_1feed/get_tweets.php',
function(feeds) {
//alert(feeds);
var feedHTML = '';
var displayCounter = 1;
for (var i=0; i<feeds.length; i++) {
var tweetscreenname = feeds[i].user.name;
var tweetusername = feeds[i].user.screen_name;
var profileimage = feeds[i].user.profile_image_url_https;
var status = feeds[i].text;
var isaretweet = false;
var isdirect = false;
var tweetid = feeds[i].id_str;
//If the tweet has been retweeted, get the profile pic of the tweeter
if(typeof feeds[i].retweeted_status != 'undefined'){
profileimage = feeds[i].retweeted_status.user.profile_image_url_https;
tweetscreenname = feeds[i].retweeted_status.user.name;
tweetusername = feeds[i].retweeted_status.user.screen_name;
tweetid = feeds[i].retweeted_status.id_str
isaretweet = true;
};
//Check to see if the tweet is a direct message
if (feeds[i].text.substr(0,1) == "#") {
isdirect = true;
}
//console.log(feeds[i]);
if (((showretweets == true) || ((isaretweet == false) && (showretweets == false))) && ((showdirecttweets == true) || ((showdirecttweets == false) && (isdirect == false)))) {
if ((feeds[i].text.length > 1) && (displayCounter <= displaylimit)) {
if (showtweetlinks == true) {
status = addlinks(status);
}
if (displayCounter == 1) {
feedHTML += headerHTML;
}
feedHTML += '<div class="twitter-article">';
feedHTML += '<div class="twitter-pic"><a href="https://twitter.com/'+tweetusername+'" ><img src="'+profileimage+'"images/twitter-feed-icon.png" width="42" height="42" alt="twitter icon" /></a></div>';
feedHTML += '<div class="twitter-text"><p><span class="tweetprofilelink"><strong><a href="https://twitter.com/'+tweetusername+'/status/'+tweetid+'">'+relative_time(feeds[i].created_at)+'</span><br/>'+status+'</p></div>';
feedHTML += '</div>';
displayCounter++;
}
}
}
$('#twitter-feed').html(feedHTML);
});
//Function modified from Stack Overflow
function addlinks(data) {
//Add link to all http:// links within tweets
data = data.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return '<a href="'+url+'" >'+url+'</a>';
});
//Add link to #usernames used within tweets
data = data.replace(/\B#([_a-z0-9]+)/ig, function(reply) {
return '<a href="http://twitter.com/'+reply.substring(1)+'" style="font-weight:lighter;" >'+reply.charAt(0)+reply.substring(1)+'</a>';
});
return data;
}
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
var shortdate = time_value.substr(4,2) + " " + time_value.substr(0,3);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return '1m';
} else if(delta < 120) {
return '1m';
} else if(delta < (60*60)) {
return (parseInt(delta / 60)).toString() + 'm';
} else if(delta < (120*60)) {
return '1h';
} else if(delta < (24*60*60)) {
return (parseInt(delta / 3600)).toString() + 'h';
} else if(delta < (48*60*60)) {
//return '1 day';
return shortdate;
} else {
return shortdate;
}
}
});
This is the get_tweets.php script where I encode the results in a JSON format.
<?php
session_start();
require_once('twitteroauth/twitteroauth/twitteroauth.php');
$twitteruser = "jackcoldrick";
$notweets = 30;
$consumerkey="xxxxxxxxxxxxxx";
$consumersecret="xxxxxxxxxxxxxxx";
$accesstoken="xxxxxxxxx";
$accesstokensecret="xxxxxxxxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret){
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
echo json_encode($tweets);
?>
This seems doable with your current code. Things to consider:
I'm not sure, but Twitter might have a limit on requests (I imagine it's not a huge one)
Just encapsulate the reusable parts of your code in a function called updateTweets, and call that with a setInterval. There isn't anyway to really "push" tweet updates to your JavaScript, that I know of.
I would put your update code into a function that has a SetTimeout() that does a recursive call to the new function every x seconds. An example below.
$(document).ready(function () {
// Call to your update twitter function
updateTwitter(data);
});
function updateTwitter(data) {
// do your original update twitter GET
$.getJSON('http://www.jdiadt.com/twitterv1_1feed/get_tweets.php', function () {
//... all that code
});
// Sets a timer that calls the updateTwitter function 1x a minute
setTimeout(function () { updateTwitter(data); }, 60000);
}

Categories