Getting the src from images set true foreach loop with the src from the model asp.net razor [duplicate] - javascript

This question already has answers here:
How to get the onclick calling object?
(5 answers)
Closed 4 years ago.
I am trying to get the img src for a javascript function.
But the images were set true a foreach loop and the src of the image are send from the model like this
#{
foreach (var image in Model.ImagesInFile)
{
var imageFile = "/Content/images/" + image;
<div class="image_holder">
<img id="img_tumb" class="images_display" src="#imageFile" alt="testimage" onclick="show_pic()" />
</div>
}
}
What I'm trying to do is when I click on an image that image should be displayed with javascript in a div that I have,
<div class="image_showcase" id="img_show">
</div>
But how do get the source of the image that is clicked ??
I tried this,
<script>
function show_pic() {
if ($('#img_show').find('img').length > 0) {
alert("same image");
} else {
var img_src = document.getElementById('img_tumb').src;
var img = document.createElement("img");
img.src = img_src;
document.getElementById('img_show').appendChild(img);
}
}
</script>
But when I click on any image I will always get the first image in the list, it doesn't matter what image I clicked !?

Looks like you assign same id for all your images.
Don't forget to pass the id as function parameter.
#{
var count = 0
foreach (var image in Model.ImagesInFile) {
count ++
var id = "img_tumb" + count
var imageFile = "/Content/images/" + image;
<div class="image_holder">
<img id="#id" class="images_display" src="#imageFile" alt="testimage" onclick="show_pic(#id)" />
</div>
}
}
<script>
function show_pic(id) {
if ($('#img_show').find('img').length > 0) {
alert("same image");
} else {
var img_src = document.getElementById(id).src;
var img = document.createElement("img");
img.src = img_src;
document.getElementById('img_show').appendChild(img);
}
}
</script>

Related

Dynamically add <img> tags with via PHP loop, via calling a JavaScript function on each loop

I have a PHP function that loops through image results in a database, formats them with HTML, then returns the variable containing the HTML layout to my page.php. This is all working okay, but in the loop I have some script tags that call a function in my script.js file. It takes two parameters (url and count). I am trying to pass the url of the result from the database to the function, create a new img element, and append the passed url to the src attribute of the newly created img tag.
This appears to be working so far - when I console.log the result, I get a load of <img> tags, all with corresponding src attached to them.
I am having trouble with actually getting these back to the front end, though.
My code below shows the part of the php that gets looped through, followed be the Javascript function it calls on each loop.
public function getResultsHtml($page, $pageSize, $term) {
$fromLimit = ($page - 1) * $pageSize;
$query = $this->con->prepare("SELECT * FROM images
WHERE (title LIKE :term
OR alt LIKE :term) AND broken=0
ORDER BY clicks DESC
LIMIT :fromLimit, :pageSize");
$searchTerm = "%" . $term . "%";
$query->bindParam(":term", $searchTerm);
$query->bindParam(":fromLimit", $fromLimit, PDO::PARAM_INT);
$query->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$query->execute();
$resultsHtml = "<div class='image-results'>";
$count = 0;
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$count++;
$id = $row["id"];
$imgUrl = $row["imgUrl"];
$siteUrl = $row["siteUrl"];
$title = $row["title"];
$alt = $row["alt"];
if($title){
$displayText = $title;
} else if ($alt) {
$displayText = $alt;
} else {
$displayText = $imgUrl;
}
$resultsHtml .= "<div class='grid-item image$count'>
<a href='$imgUrl'>
<script>
document.addEventListener('DOMContentLoaded', function() {
loadImage(\"$imgUrl\", \"image$count\");
});
</script>
<span class='details'>$displayText</span>
</a>
</div>";
}
$resultsHtml .= "</div>";
return $resultsHtml;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
aTag.innerHTML = image;
};
image.onerror = function(){
};
image.setAttribute("src", src);
}
At the moment I'm not geting any results at the front end. In the page source, I can see that inside each anchor tag are script tags, which show the function preloaded with the parameters (loadImage(http://www.com, image22)), but it isn't actually getting a return from the function.
The solution for this with jQuery is below, but I really don't want to use jQuery!
function loadImage(src, className) {
var image = $("<img>");
image.on("load", function() {
$("." + className + " a").append(image);
});
image.on("error", function() {
});
image.attr("src", src);
}
I know that there is some trouble with dynamically writing <script> tags with .innerHTML, but I don't think this is the problem as the script tags are written before the function is called.
I think I have something firing in the wrong order, or I'm missing something that jQuery handles automatically with the .append function.
I have also tried aTag.appendChild(image);, which also gives no results.
I have been using jQuery for a few months, but I am trying to learn Vanilla JS thoroughly - I'm trying to grasp how the jQuery functions actually work, rather than just relying on them blindly.
Any help is massively appreciated!
Beware of that querySelectorAll() returns an array-like NodeList (https://developer.mozilla.org/en-US/docs/Web/API/NodeList), so it should be like this:
(If you only want one element returned user querySelector(), then you don't need the loop)
function loadImage(src, className) {
var image = document.createElement("img");
image.src = src;
image.onload = function() {
var tags = document.querySelectorAll("." + className + " a");
for (var i = 0; i < tags.length; i++) {
tags[i].appendChild(image);
}
}
}
<div class='grid-item image2'>
<a href='https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg'>
<script>
document.addEventListener('DOMContentLoaded', function() { loadImage("https://cdn.pixabay.com/photo/2015/08/21/21/55/star-wars-899693_960_720.jpg", "image2");
});
</script>
<span class='details'>Star Wars 1</span>
</a>
</div>
The problem is that you are using querySelectorAll, which returns a NodeList instead of a single DOM node. This means, you have to iterate over the NodeList and append the image to all the nodes within. For this, you have can either create new copies for each place you want to insert the image, or use cloneNode multiple times.
var each = function (xs, func) {
for (var i = 0; i < xs.length; i += 1) {
func(xs[i]);
}
return xs;
}
var loadImage = function(src, className){
var image = document.createElement("img");
var aTag = document.querySelectorAll("." + className + " a");
image.onload = function(){
each(aTag, function (a) {
a.appendChild(image.cloneNode());
});
};
image.onerror = function(){};
image.alt = '';
image.src = src;
}
loadImage('http://www.fillmurray.com/500/300', 'wrap')
<div class="wrap">
</div>

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

getElementById() is null?

So I am trying to make a JavaScript program that will take a URL for an image and then put it onto the page while creating an <img> tag so that I can just continue pasting as many photos as I want. Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Low-Budget Online Album</title>
<meta charset="utf-8">
<script>
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
imageInput.value = "";
}
}
</script>
</head>
<body>
<input type="text" id="imageInput" size="40" placeholder="Image Source">
<input type="button" id="addButton" value="Add Image">
<img id="images" src="">
</img>
</body>
</html>
My problem is, is that when I put int a URL (or picture src from my PC) it says that TypeError: document.getElementById(...) is null, and points to line 20, being my
var newSrc = document.getElementById("newImage").src= imageSource;
line. Any ideas?
Use this
else {
var newImage = document.createElement("img"); //this line creates element <img> element in the dom.
newImage.setAttribute("id", "newImage");
newImage.src= imageSource;
document.body.appendChild(newImage);//adds element <img src="a.jpg" id='newImage'>to the dom.
imageInput.value = "";
}
Understand what mistake you have done above:
1.First you created element and assign to a variable newImage
var newImage=document.createElement("img");
2.You are calling
document.getElementById('newImage');
Here newImage as element that you created and in the dom there is no element with id as newImage so you were getting null.
do you mean something like this:
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
newImage.src= imageSource;
newImage.setAttribute("id", "newImage");
imageInput.value = "";
document.body.appendChild(newImage);
}
}
Demo:: jsFiddle
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
Become:
var newImage = document.createElement("img");
newImage.setAttribute('id','newImage');
var newSrc = document.getElementById("newImage").src = imageSource;
in mdn you can see that createElement only create element and not add it to DOM. So if you want add created element you need change your code like this
var newImage = document.createElement("img");
newImage.id = "newImage";
document.body.appendChild(newImage);
after this line will work
var newSrc = document.getElementById("newImage").src= imageSource;
but you don't need get find it if you already have this image in newImage variable, so this line you can change like
var newSrc = newImage.src= imageSource;
UPDATE
Possibly you need use className instead of id because id should be unique on page, but as i understand you want add many images

Get Image Source URLs from a Different Page Using JS

Everyone:
I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.
Page 1 is just a page with images:
<html>
<head>
</head>
<body>
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</body>
</html>
Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)
<script type = "text/javascript">
var days = 730;
var rotator = new Object();
var currentTime = new Date();
var currentMilli = currentTime.getTime();
var images = [], index = 0;
images[0] = "image0.jpg";
images[1] = "image1.jpg";
images[2] = "image2.jpg";
images[3] = "image3.jpg";
rotator.getCookie = function(Name) {
var re = new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1];
return'';
}
rotator.setCookie = function(name, value, days) {
var expireDate = new Date();
var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}
rotator.randomize = function() {
index = Math.floor(Math.random() * images.length);
randomImageSrc = images[index];
}
rotator.check = function() {
if (rotator.getCookie("randomImage") == "") {
rotator.randomize();
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
if ( currentMilli > writtenTime + 10000 ) {
rotator.randomize();
var writtenImage = rotator.getCookie("randomImage")
while ( randomImageSrc == writtenImage ) {
rotator.randomize();
}
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenImage = rotator.getCookie("randomImage")
document.write("<img src=" + writtenImage + ">");
}
}
}
rotator.check()
</script>
Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.
Please let me know if I can clarify!
Try this.
<script>
$.get('http://path/to/page/1', function(data) {
var imgs = $('<div/>').html(data).find('img');
imgs.each(function(i, img) {
alert(img.src); // show a dialog containing the url of image
});
});
</script>
I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.
$.get('page1.html', function(data, status) { // get the page with the images
var parser = new DOMParser();
var xmldoc = parser.parseFromString(data, "text/html"); //turn it into a dom
var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
return img.src; //convert them to an array of sources
});
setInterval(function() { // run this every 10 seconds
var imags = document.getElementsByTagName('img'); // find the images on this page
Array.prototype.slice.call(imgs).forEach(function(img) {
var imgSrc = Math.floor(Math.random()*imageSrcs.length); //get a random image source
img.src = imageSrcs[imgSrc]; //set this image to the src we just picked at random
});
}, 10000);
}, 'html');
why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.
external.html
<html>
....
<div id="imgContainer">
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</div>
</html>
ajax.js
function ajaxContent(reg, extReg) {
var toLoad = 'external.html' + extReg;
function loadContent() {
$(reg).load(toLoad,'',getSrcPaths())
}
function getSrcPaths() {
$(reg + ' #image0').delay(200).fadeIn('slow');
$(reg + ' #image1').delay(200).fadeIn('slow');
// or however you want to store/display the images
}
}
Then onload just make a call to ajaxContent something like
<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
....
</body>
This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

How to integrate a series of images to form an HTML page?

I have a series of images (named as image_1.jpg, image_2.jpg and so on) in a folder. How can all of the images be joined together to form an HTML page using Javascript?
Just add:
<img src="path/to/your/image_1" alt="image_1" />
<img src="path/to/your/image_2" alt="image_2" />
<img src="path/to/your/image_3" alt="image_3" />
etc...
EDIT:
for(var i = 1 ; i < TOTAL_IMAGES ; i ++ )
{
var img = document.createElement('img');
img.src = "path/to/your/image_" + i;
img.alt = "image number " + i;
document.appendChild(img); // this will append the image to the root element. You might want to use a <div> or something instead.
}

Categories