Why Isn't the jQuery .index() function behaving like I expect here? - javascript

I am having issues understanding why my jQuery index() function is not performing the way I expect it to. Perhaps I'm not understanding this. Let me show you.
I set up a new array. We'll use this later:
var mySources = new Array();
I have 5 images on my page:
<div id="homeSlides">
<img src="../images/homeImages/00.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/01.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/02.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/03.jpg" width="749" height="240" alt="myAltTag" />
<img src="../images/homeImages/04.jpg" width="749" height="240" alt="myAltTag" />
I put them all in an jQuery object, like this:
var myImages = $("#homeSlides img");
Now, for each one, I extract the src attribute and push it into the mySources array like this:
$(myImages).each( function(index) {
mySources[index] = $(this).attr('src');
});
Now, I will run the array to the FireBug console to make sure it worked.
This...
console.log(mySources);
...returns this...
["../images/homeImages/00.jpg", "../images/homeImages/01.jpg", "../images/homeImages/02.jpg", "../images/homeImages/03.jpg", "../images/homeImages/04.jpg"]
...which is what I expect.
Now I do this:
var myVar = $(myImages).eq(2).attr('src');
Tracing that variable now...
console.log(myVar);
...returns this...
../images/homeImages/02.jpg
But then when I do this...
console.log('Index of ' + myVar + " is: " + ($(myVar).index( mySources )) );
...it returns this:
Index of ../images/homeImages/02.jpg is: -1
This is throwing me. Why would it return -1 for "not found" when it should be retunring 2. It does mat the second slot in the mySources array, no?

You are trying to use index() on an array. It is not intended to be used for anything other than jQuery element objects.
Using $.inArray() would be the better method

You may have the function backwards. Can you try:
$(mySources).index( myVar )

Related

get Attribute to insert it in my src ??, I do not know too much help me

The result that I get "undefined":
code js:
document.getElementById("myImg").src = "hackanm"+x+".gif";
var x = document.getElementsByTagName("img")[0].getAttribute("data");
HTML:
<img data="WhatIWantToAdd" id="myImg" src="" >
The ordering was wrong. Even though x is declared, it's values is used before assignment. Hence the undefined
var x = document.getElementsByTagName("img")[0].getAttribute("data");
document.getElementById("myImg").src = "hackanm"+x+".gif";
<img data="WhatIWantToAdd" id="myImg" src="" >

How to perform replace in a loop in js

I have a string like this
var string = '<img src="test.jpg'><img src="test2.jpg>';
var dom = new JSDOM(string,{ includeNodeLocations: true });
dom = dom.window.document.querySelectorAll("img");
for(var i = 0;i< dom.length;i++) {
text = string.replace(/<img[^>]*>/g,'<amp-img layout="responsive" class="ampimageheight" src="'+dom[i].getAttribute('src')+'" width="200" height= "100"></amp-img>');
}
But my output is
<amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img><amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img>
In which only the second image src is replaced for 2 imags.I think this is because of the asynchronous.Can anyone please help me.Thanks.
Well, if you run replace in a loop, you don't need set the Regex's flag.
Because that replace all img when first time loop.
After first loop is do nothing.
So, you can remove Regex flag, or use a callback replace your function's second arguments, like this.
text = string.replace(/<img[^>]*>/g, function(str, index){
return '<amp-img layout="responsive" class="ampimageheight" src="'+dom[index].getAttribute('src')+'" width="200" height= "100"></amp-img>'
});
And it doesn't need loop;

Automatically loading a series of images sequentially in html

I have a html page that gets automatically refreshed every 1 ms. I did it using mata tag:
<html>
<head>
<title>My Page</title>
<meta http-equiv="refresh" content="0.001">
</head>
<body>
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
</body>
</html>
Now my requirement is such that after every refresh I must load a new file. So in my folder I have files named: 0.bmp, 1.bmp, 2.bmp,... 1000.bmp, which will be loaded on the html file. i.e after every refresh a new file from the folder will be loaded. Basically the file name in
<img src=" 0.bmp" alt="Smiley face" height="100" width="200" />
will change from 0.bmp to 1...1000.bmp and so on.
How can we do this in html i.e change the file name dynamically?
Edited #1:
I have just realized that my problem is basically of animation. So given 1000 images stored in hard disk, I have to play them one by one on an HTML page. This should be as fast as possible. The only requirement is it must be on html pages, this is because these HTML pages will be accessed from a client in a network. the problem that I am thinking is slow playback because read/write to the disk may not be fast.
Edited # 2
After getting inputs from following answers, I was able to animate the images. The issue right now I am facing is the display rate is too small, and so fluctuations are coming up. I understand this is a problem of slow read/write from hard disk. So I guess if I can put these images in buffer i.e: System RAM, and write a html/js code to access the images from the RAM instead of the disk, the play back will be much faster. Can someone send me a sample code to, write images in RAM and use html/js code to access these images from RAM?
Note: as per the policy of stackoverflow, I am updating my question as and when I am solving various steps of the original problem.
What you are trying to do should not be done by refreshing continuously the web page, but by the use of Javascript.
Consider this method using JQUERY and setInterval():
See a working Fiddle Example!
HTML
<html>
<head>
<title>My Page</title>
</head>
<body>
<img src="path_to_image_01.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_02.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_03.jpg" alt="Smiley face" height="128" width="128" />
<img src="path_to_image_04.jpg" alt="Smiley face" height="128" width="128" />
</body>
</html>
JQUERY
$(document).ready(function() {
$('img:not(:first)').hide();
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
});
What's being done
Hide all images
`$('img:not(:first)').hide();`
Initialize an interval of 1 sec that will collect the first image,
hide it, jump to the next image, show it, lastly move the previous
image to the end.
var refreshId = setInterval( function()
{
var $target = $('body img:first');
$target.hide().next().show();
$target.appendTo('body');
}, 1000);
This keeps on going animating the images every second that passes.
I am updating my answer based on a now different question.
You can use this plugin: https://code.google.com/p/jsmovie/ It does exactly what you want by animating a set of images.
Original Answer Below:
Although I'd agree with many of the other answers, it seems the OP needs to refresh the entire window instead of doing this via ajax without a page reload.
<img src="" alt="Smiley face" height="100" width="200" style="display:none" />
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var imgIndex = 0;
$(document).ready(function() {
if (getParameterByName("index")!='') {
imgIndex = parseInt(getParameterByName("index"));
}
$('img').attr('src', imgIndex + '.bmp').show();
var refreshId = setInterval( function()
{
imgIndex++;
location.href = location.pathname + "?index=" + encodeURIComponent(imgIndex);
}, 1000); // 1 second update as needed
});
The following fiddle demonstrates this though I dont' have a serial set of images so the jsfiddle is a little different in that it updates an index of already set images forked from a previous answer but it does demonstrate the page reload.
http://jsfiddle.net/smf9w/1/
​
DON'T, really DON'T do this!!
Use JS instead. Use setInterval() and use a time span greater than 1m...
As others say, this is not the way to do it. But you can use cookie or localstorage on modern browsers.
function getData() {
var c = 0;
if ("localStorage" in window && null !== window.localStorage)
c = localStorage.count;
else {
count = document.cookie.split("count=");
c = c[1].split(";");
c = c[0];
}
return c;
}
function updateData(count){
if ("localStorage" in window && null !== window.localStorage)
localStorage.count = count;
else {
var e = new Date;
e.setTime(e.getTime() + 31536E6);
e = e.toGMTString();
document.cookie = "count=" + count + "; expires=" + e + "; path=/"
}
}
var count = getData();
document.write('<img src="'+ count +'".bmp" alt="Smiley face" height="100" width="200" />');
updateData(++count);
Code above is just a sample.

javascript regex - replace each match of given expression with different string

I have a string contaning some html markup, like this:
var html = "<div>
<img src="http://test.com/image1.png" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>";
i want to replace all urls inside src="..."
It is ok if i do html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, "SOME_URL");
then all src="..." become src="SOME_URL"
But now i want to replace each match with a different string, taken from an array, but i'm having trouble with this.
I think i have to use a function for the replacement, but not sure how to implement it.
Something like:
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){ //what do i do here??? });
So, if i have:
var arr = [];
arr['http://test.com/image1.jpg']='file1';
arr['http://test.com/test.jpg']='file3';
the html string from above will become:
"<div>
<img src="file1" />
<h1>SOME TEXT</h1>
<img src="http://text.com/image2.jpg" />
</div>"
Note that 'http://text.com/image2.jpg' is not a key of the array, so it does not gets replaced.
Any help appreciated, thank you in advance.
var html = '<div><img src="http://test.com/image1.jpg" />...</div>';
var arr = {
'http://test.com/image1.jpg' : 'file1',
'http://test.com/test.jpg' : 'file3'
}
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){
return ' src="' + (arr[$1] || $1) + '"';
});
console.log(html) returns
"<div><img src="file1" /><h1>SOME TEXT</h1><img src="http://text.com/image2.jpg" /></div>"
I'd forget about regex in this case, if you have an array containing all urls and their individual replacements in an object, why not do something like:
for (i in replaceObj)
{
html = html.split(i).join(replaceObj[i]);
}
tried it in console:
html = '<div><img src="imgs/img.jpg"/></div>';
replaceObj = {};
replaceObj['imgs/img.jpg'] = 'file';
for(i in test){html = html.split(i).join(replaceObj[i])};
output: <div><img src="file"/></div>. You could split on src="'+i'"' and concat. the same when joining to be on the safe side... but bottom line: keep it simple, whenever you can

JS Image change won't work under other tags (should be a simple fix)

Hey guys,
basically this is my page and the JS simply changes the images if one is clicked, this works grand if the <img src='worseun.png' name='worse' border='0' /> is first beneath the <body>, but doesn't work if there is another <img src='' /> above it! I'm still learning js and this is a head wreck, can anyone suggest a fix? Heres it working with nothing above
<script type="text/javascript">
function worseChange()
{
var theImga = document.getElementsByTagName('img')[0].src;
var xa = theImga.split("/");
var ta = xa.length-1;
var ya = xa[ta];
if(ya=='worseun.png')
{
document.images.worse.src='worse.png';
document.images.cd.src='cdun.png';
}
}
function cdChange()
{
var theImgb = document.getElementsByTagName('img')[1].src;
var xb = theImgb.split("/");
var tb = xb.length-1;
var yb = xb[tb];
if(yb=='cdun.png')
{
document.images.worse.src='worseun.png';
document.images.cd.src='cd.png';
}
}
</script>
</head>
<body>
<a name=1>Uno</a>
<img src='worseun.png' name='worse' border='0' /> <br />
<img src='cd.png' name='cd' border='0' />
<a name=2>Dos</a>
<body>
Thanks guys,
James
That first line:
var theImga = document.getElementsByTagName('img')[0].src;
means, "get the very first <img> tag in the document, and then fetch its 'src' attribute value." You can instead give the "real" image an "id" value, and use document.getElementById('whatever') to get it.
<img id='worse' src='worseun.png' name='worse' border='0' />
and then
var theImga = document.getElementById('worse').src;

Categories

Resources