Get .src in Javascript from PHP while - javascript

I have a folder with a couple of images. I´m using PHP to get the path of each image to show them in a HTML <table>. Now i´m trying to use the addEventListener to show the image in another div. I begin to show you my PHP:
<table id="imgTable">
<tr>
<?php
$handle = opendir(dirname(realpath(_FILE_)).'../up/to/my/folder');
while($file = readdir($handle)) {
if($file !== '.' && $file !== '..') {
echo '<tr><img src="../up/to/my/folder/' .$file. '" alt="image" class="imgClass"></td>';
}
}
?>
</tr>
</table>
After that i want to use the addEventListener to get the URL from the clicked image and use the src to display the image in another div. Like a photo-gallary.
Thats what I have in JS:
<script type="text/javascript">
document.getElementsByTagName('img').addEventListener("click", function(){
document.getElementById('imgViewer').style.visibility= "visible";
var img = document.getElemensByClassName('imgClass');
for(i=0; i<img.length; i++) {
document.getElementById('bigImg')src = img[i].src;
}
}
</script>
After that, I use to show the image in a with CSS hidden div:
<div id="imgViewer">
<img src="../up/to/my/folder/imgholder.png" id="bigImg">
</div>
I dont want to use onClick. But there comes no reaction with addEventListener and I don´t understand why. It´s my first year in the University and I had just begun to write JavaScript. Maybe there is somebody to help me.

ID should be unique in both HTML4 and HTML5.
http://www.w3.org/TR/html4/struct/global.html
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
http://www.w3.org/TR/html5/dom.html#the-id-attribute
The id attribute specifies its element's unique identifier (ID). [DOM]
You can modify your PHP and JavaScript code as following
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>OnClick</title>
</head>
<body>
<table id="imgTable">
<tr><?php
$handle = opendir(dirname(realpath(_FILE_)).'../up/to/my/folder');
$imgID = 0;
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo ' <td><img src="../up/to/my/folder/' .$file. '" alt="image" class="imgClass" id="imageId_'.$imgID.'"></td>\n';
$imgID++;
}
}
?></tr>
</table>
<div id="imgViewer">
<img src="../up/to/my/folder/imgholder.png" id="bigImg">
</div>
<script type="text/javascript">
// create array of all images inside "imgTable"
var imglist = document.getElementById("imgTable").getElementsByTagName("img");
// loop to create onclick event for each image
for(i=0; i<imglist.length; i++) {
document.getElementById(imglist[i].id).addEventListener("click", function(){
document.getElementById('bigImg').src = this.src;
});
}
</script>
</body>
</html>
code is tested and working...
You can run following snippet for demo (I replace images and manually add html code instead of php part)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>OnClick</title>
</head>
<body>
<table id="imgTable">
<tr>
<td><img src="http://i.imgur.com/99ACX4d.jpg" alt="image" class="imgClass" id="imageId_1"></td>
<td><img src="http://i.imgur.com/lXVuaa3.jpg" alt="image" class="imgClass" id="imageId_2"></td>
</tr>
</table>
<div id="imgViewer">
<img src="http://i.imgur.com/QsYVnSd.png" id="bigImg">
</div>
<script type="text/javascript">
// create array of all images inside "imgTable"
var imglist = document.getElementById("imgTable").getElementsByTagName("img");
// loop to create onclick event for each image
for(i=0; i<imglist.length; i++) {
document.getElementById(imglist[i].id).addEventListener("click", function(){
document.getElementById('bigImg').src = this.src;
});
}
</script>
</body>
</html>
Also format your code and use some code editor with autocomplete and debugger. You have many small mistakes (e.g. <tr> instead of <td> in php echo, you forgot dot (.) before src in JS, there is no t in getElementsByClassName).

replace this line
document.getElementById('bigImg')src = img[i].src;
with
document.getElementById('bigImg').src = img[i].src;
you forgot . berfore src
and try this for click event
document.getElementsByTagName('img').addEventListener("click", function() {}
seems like your all images has same id so it will not apply on all images, id have to be unique
you can also do this in jquery for click
$('.imgClass').click(function(){
});

first give a same class name to all images(for example class name is test) and then
write below code
$('.test').on('click',function(){
var src = $(this).attr('src');
// here place your rest of the code
});

Related

How to switch 4 images using a button

<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.
Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.
Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>
What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>

Why is jQuery(document).ready not working? / How do I add CSS to an element in jQuery?

I'm new to jQuery and I'm having problem with a piece of code.
I'm trying to add Image Power Zoomer v1.2 to my website, which works on the main image, but not the rollover image! The rollover image changes, but power zoomer only shows the loading image.
This is an example URL: Example1
This is my code:
<script type="text/javascript">
var bufferImage = new Array();
function Buffer(filename) {
var i = bufferImage.length;
bufferImage[i] = new Image();
bufferImage[i].src = filename;
}
function showImage(filename) {
document.images[Image_Name].src = filename;
}
Image_Name = "image_pal";
Buffer("thumbnail.php?pic=<? echo $image_pal['media_url'];? >&w=600&sq=Y");
jQuery(document).ready(function($){ //fire on DOM ready
$('#myimage').addpowerzoom({
powerrange: [2,8],
largeimage: null,
magnifiersize: [200,200] //<--no comma following last option!
})
})
</script>
<? $sql_image_pal=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");
$image_pal=$db->fetch_array($sql_image_pal);
$sql_image=$db->query("SELECT media_url FROM " . DB_PREFIX . "auction_media WHERE auction_id='" . $item_details['auction_id']."'AND media_type=1 ORDER BY media_id ASC ");?>
<div align="center" class="image_pal">
<? if (empty($image_pal['media_url'])) {?>
<img src="themes/<?=$setts['default_theme'];?>/img/system/noimg.gif" name="image_pal" width="600" />
<? } else {?>
<img id="myimage" src="thumbnail.php?pic=<?=$image_pal['media_url'];?>&w=600&sq=N" border="0" alt="<?=$item_details['name'];?>" name="image_pal" />
<? }?>
</div>
<div class="list_carousel_img" align="center">
<ul id="small_img">
<? while($image=mysql_fetch_array($sql_image)){?>
<? $ad_img=$image['media_url'];?>
<li class="small_img">
<a href="thumbnail.php?pic=<? echo $ad_img;?>" onmouseover="showImage('thumbnail.php?pic=<?=$image['media_url'];?>&w=600&sq=Y')"class="lightbox" rel="thumbnail_images" ><img src="thumbnail.php?pic=<?=$image['media_url'];?>&w=60&sq=Y" border="0" alt="<?=$item_details['name'];?>"/></a>
</li>
<? } ?>
</ul>
<div class="clearfix"></div>
<a id="prev_img" class="prev_img" href="#"></a>
<a id="next_img" class="next_img" href="#"></a>
<? if ($setts['lfb_enabled'] && $setts['lfb_auction']) { ?>
<div><img src="themes/<?=$setts['default_theme'];?>/img/pixel.gif" width="1" height="5"></div>
<? include("scripts/scroller/show_rep_details.php"); ?>
<? } ?>
I'm having trouble with jQuery Selectors. I have looked all over the web, spent many hours, but with no joy.
This is the site i got the Image Power Zoomer v1.2 from:
dynamicdrive.com
Question #2
Like i said im a newbie but i think my problems here jQuery selector these are some examples but i do not know what i need to add from my code
<script type="text/javascript">
jQuery(document).ready(function($){ //fire on DOM ready
$('img.showcase').addpowerzoom() //add zoom effect to images with CSS class "showcase"
$('#gallerydiv img').addpowerzoom() //add zoom effect to all images inside DIV with ID "gallerydiv"
})
</script>
What do i need to add here
$('????????????').addpowerzoom()
Thanks For all your help
jQuery(document).ready(function($){ //fire on DOM ready
==>
$(document).ready(function(){ //fire on DOM ready
Unless you changed your jQuery selector, this is the default
Because you asked another question in the answers (and even got an upvote?)
What do i need to add here
$('????????????').addpowerzoom()
This is my answer to that question:
$("img").each(function(){
$(this).addpowerzoom();
});
like in this demo: http://jsfiddle.net/u7w0ppq9/ with adding class instead of powerzoom (I do not have that library so, but it's basically the same)

getting a Cannot set property 'value' of null message when trying to change what's in an image tag

here is my code. it works when i replace $("defaultimage").value = imgStr; with a document.write statement, but I don't want to use a doc.write statement. Any tips on what I am doing wrong? Thanks in advance - javascript noob.
<html lang="en">
<head>
<meta charset="UTF-8"
<title></title>
<link rel="stylesheet" href="ColorPerceptionTest.css">
</head>
<body>
<section>
<img src="Default.png" name="defaultimage">
<form>
<input type="button" value="Button1" onClick="getRandomImage(imagesArray)">
<input type="button" value="Button2" onClick="()">
<input type="button" value="Button3" onClick="()">
<br>
<input type="button" value="Start" onClick="()">
<input type="button" value="Help" onClick="()">
</form>
</section>
<script>
var $ = function(id) {
return document.getElementById(id);
}
var imagesArray = ["1.gif", "2.gif", "3.gif", "4.gif", "5.gif", "6.gif", "7.gif",
"8.gif", "9.gif", "10.gif", "11.gif", "12.gif", "13.gif",
"14.gif", "15.gif"];
function getRandomImage(imgAr, path) {
path = path || 'images/'; //gets the default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
$("defaultimage").value = imgStr;
}
</script>
</body>
Your selector is wrong. Right now using $("defaultimage") you're trying to select an elemnt <defaultimage></defaultimg> Try instead $('img[name="defaultimage"]'). This is targeting an img tag with the name attribute of 'defaultimage'.
Also if you want to change the src of the img tag you cannot do it like this. Try instead $('img[name="defaultimage"]').attr('src',newsource) where newsource is a variable containing the new source you would like the image tag to have.
Well, there are a lot of things wrong here. haha. Using a class or id on the image would make even more sense.
Give it a go with this information and let me know if you need additional information.
your selector should be:
$("image[name='name']")
please read this article for further info:
http://www.javascriptkit.com/dhtmltutors/css_selectors_api.shtml
Your var $ is a getElementById, you should pass the id of the img element to it, instead of name. Change your <img src="Default.png" name="defaultimage"> to <img src="Default.png" id="defaultimage">, it will work.

JQuery each function to fill array with attributes from HTML images

I'm trying to load an array filled with the src attribute from a series of img tags in my HTML document.
HTML:
<html>
<head>
<title>
JQuery Slider
</title>
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div id = "wrapper">
<h1 class="dark-header">2014 Salt Lake Comic Con FanX</h1>
<div id="background-img">
<img src="img/img01.jpg"/>
</div>
<div>
<img src="img/img02.jpg"/>
</div>
<div>
<img src="img/img03.jpg"/>
</div>
<div>
<img src="img/img04.jpg"/>
</div>
<div>
<img src="img/img05.jpg"/>
</div>
<div>
<img src="img/img06.jpg"/>
</div>
<div>
<img src="img/img07.jpg"/>
</div>
<div>
<img src="img/img08.jpg"/>
</div>
<div>
<img src="img/img09.jpg"/>
</div>
<div>
<img src="img/img10.jpg"/>
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function() {
var source = new Array();
$('img').each(function(attr) {
source.push($('img').attr('src'))
});
console.log(source)
});//end document.ready
The output to the console is an array of 10 elements, but only using the first img attribute. I'm not sure how to get the each function to go through all elements and push them to the array.
Your issue is that $('img').attr('src') will always return the value of the first element in the collection of elements.
As pointed out in comments , you need to look at specific instances within your loop
Another way you can do this is using map() which will create the array for you
var source = $('img').map(function(){
return $(this).attr('src');
}).get();
DEMO
You could try something like this:
var source = [];
$('img').each(function() {
source.push( this.getAttribute('src') );
});
In your each code, you re-select the entire group with $('img') so it is only adding the first one of THAT Selection to your array.
OR
If you aren't using jQuery for anything else, you could do it in straight javascript like this:
document.addEventListener('DOMContentLoaded', getImgAttr);
var source = [];
function getImgAttr() {
var imgs = document.querySelectorAll('img');
[].forEach.call(imgs, function( img ) {
source.push( img.src);
});
}
you need to use 'this' while inside the loop to reference the image, otherwise you are getting the reference to first 'img ' tag.
it should be like this:
$('img').each(function(attr) {
source.push($(this).attr('src'))
});
Your callback function needs to accept a second param...
The first param is the current index of the array and the second param is the object at that index.
You may also utilize the keyword this as suggested above.
Based on my answer your code would look like this:
$('img').each(function(i, img) {
source.push($(img).attr('src'));
// alternatively -> source.push($(this).attr('src'));
});
A second option you may like and puts what you're trying to do onto a single line would be to use the jQuery map function...
var source = $.map($('img'), function(img) { return $(img).attr('src'); });

change hyperlink image on click

Hi I'm trying to change the image of hyperlink on-click as follows. But the image of the select button is not changing to loading.gif. What am I doing wrong? I'm new to jquery. Thanks in anticipation
<HTML><HEAD>
<SCRIPT type=text/javascript src="jquery.js"></SCRIPT>
</HEAD>
<BODY>
<TABLE>
<TBODY>
<TR>
<TD><A id=webservice_submit href="javascript:document.frm_correction.submit()" jQuery1365443220846="2">
<IMG onmouseover="MM_swapImage('Correction subj','','http://localhost:6868/corrmgr/img/select_up.gif',0)" onmouseout=MM_swapImgRestore() name="Correction Subj" alt="Correction Subj" src="http://localhost:6868/corrmgr/img/select.gif" oSrc="http://localhost:6868/corrmgr/img/select.gif">
</A></TD></TD></TR></TBODY></TABLE>
<DIV style="DISPLAY: none" id=loading jQuery1365443220846="3"><IMG name="Please wait..." alt="Please wait while the request is being processed..." src="http://localhost:6868/corrmgr/img/bert2.gif"> </DIV>
<SCRIPT language=javascript>
var $loading = $('#loading');
$('#webservice_submit').click(function(){
$loading.toggle();
if( $loading.is(':visible') ){
alert("invoking web services");
$('#image img').attr('src', 'http://localhost:63531/corrmgr/img/loading.gif');
return ($(this).attr('disabled')) ? false : true;
}
});
$('#loading').hide();
</SCRIPT>
</BODY></HTML>
Your selector is not right. Change this:
$('#image img')
to this:
$('#image')
And give <img> the corresponding id:
<IMG id="image" ...>
I think you want to assign the Loader Image to the below image tag
<IMG name="Please wait..." alt="Please wait while the request is being processed..."
src="http://localhost:6868/corrmgr/img/bert2.gif">
If i have understand you... you change your code like below...
FROM :
$('#image img').attr('src', 'http://localhost:63531/corrmgr/img/loading.gif');
TO :
$("img[name='Please wait...']").attr('src', 'http://localhost:63531/corrmgr/img/loading.gif');

Categories

Resources