Populate an input field with an image src in javascript - javascript

I have an XHR response that returns images. I have my function in order to show the images. I am combining JQuery and JS in the same code snippet. So far all is working well:
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var lien = leselements[i].url;
//place image urls in img src
output += "<img src='" + lien + "' class='imgs'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;}
But I would like to allow users to click an image and then populate an input field ('#imageurl') with the clicked image src. Here is what I tried but it does not work.
$('.imgs img').click(function(){
$('#imageurl').val() = "";
var source = $(this).attr('src');
$('#imageurl').val() = source;
});
Any help will be greatly appreciated. TIA.

Using .val() in this way will just return the current value of #imageurl.
$('#imageurl').val()
.val is a function call that works as a getter and a setter.
To set the value, try this:
$('#imageurl').val(source);

$('#imageurl').val("");
// ...
$('#imageurl').val(source);
See the documentation.

Try this:
$('img.imgs').click(function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});
If the image will be rendered after the attachment of the event handler use this:
$('img.imgs').live('click', function(){
var src = $(this).attr('src');
$('#imageurl').val(src);
});

Thank you guys for your prompt answers. I tried all of them but they did not work for me. I then asked a friend and we finally found a way to make it work. Probably not the best or professional way but it works. Here is the solution if ever anyone needs it.
function resultat(o){
var leselements = o.query.results.bossresponse.images.results.result;
var output = '';
var no_items = leselements.length;
for(var i=0;i<no_items;i++){
var link = leselements[i].url;
//Place urls in image src and pass in 'link' parameter to the getsrc function
output += "<img src='" + link + "' onclick='getsrc(\""+link+"\")'>";
}
// Place images in div tag
document.getElementById('results').innerHTML = output;
}
function getsrc (link) {
//console.log($(this));
$('#imageurl').val("");
// var source = $(this).attr('src');
//place imageurl value by passing in the link parameter.
$('#imageurl').val(link);
}

Related

Is there a way to switch images src back to original after on.click src change event?

I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.

Attempting to change an image onclick via PHP/Javascript/HTML

I've looked at numerous other answers regarding this but haven't found a solution that has worked. I'm using a PHP page that contains some HTML code, with Javascript working some functions. Ideally I would select an image on the page, the image will become colored green as it is selected. I would then like to deselect the image and have it return to the original state. I can only get half-way there however. What am I missing? Is it something with post back?
Here's some code examples:
The HTML:<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>
The Javascript function:
function changeImage(var i){
var img = document.getElementById("imgCh" + i + ".png");
if (img.src === "images/Tooling/" + i + ".png"){
img.src = "images/Tooling/" + i + "c.png";
}
else
{
img.src = "images/Tooling/" + i + ".png";
}
}`
The "1c.png" image is the one that is selected and should replace "1.png". There are multiple divs on this page that hold multiple images, which are named 2/2c, 3/3c, which is why the var i is included. Any insight? Thanks in advance.
You could do it something like this, it would also allow for different file names.
<img class="selectable" src="/images/Tooling/1.png"
data-original-source="/images/Tooling/1.png"
data-selected-source="/images/Tooling/1c.png">
<img class="selectable" src="/images/Tooling/2.png"
data-original-source="/images/Tooling/2.png"
data-selected-source="/images/Tooling/2c.png">
 
var images = document.getElementsByClassName('selectable');
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
function selectElementHandler(event) {
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
image.setAttribute('src', newSrc);
}
 
With comments:
// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');
// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
image.addEventListener('click', selectElementHandler);
}
// the handler receives the event from the listener
function selectElementHandler(event) {
// the event contains lots of data, but we're only interested in which element was clicked (event.target)
var image = event.target,
currentSrc = image.getAttribute('src'),
originalSrc = image.getAttribute('data-original-source'),
selectedSrc = image.getAttribute('data-selected-source'),
// if the current src is the original one, set to selected
// if not we assume the current src is the selected one
// and we reset it to the original src
newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;
// actually set the new src for the image
image.setAttribute('src', newSrc);
}
Your problem is that javascript is returning the full path of the src (you can try alert(img.src); to verify this).
You could look up how to parse a file path to get the file name in javascript, if you want the most robust solution.
However, if you're sure that all your images will end in 'c.png', you could check for those last 5 characters, using a substring of the last 5 characters:
function changeImage(var i){
var img = document.getElementById("imgCh" + i);
if (img.src.substring(img.src.length - 5) === "c.png"){
img.src = "images/Tooling/" + i + ".png";
}
else
{
img.src = "images/Tooling/" + i + "c.png";
}
}

Jquery: Get each image src

I have a series of images each with the class "photo";
I want to go through each of these and retrieve the photo source, for use later in an if statement. I have written the below code to do this, but have not been successful:
$.each($(".photo"), function() {
var imgsrc = $(this).attr("src").length;
console.log(imgsrc);
});
I am not sure where I have gone wrong here. It seems to make sense to me, but I dont get anything in the console.
Can anyone point me in the right direction?
If you have given same class name for all img tag then try this ,
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
$(document).ready(function(){
$(".photo").each(function() {
imgsrc = this.src;
console.log(imgsrc);
});
});
May be you are missing doc ready handler:
$(function(){
$.each($(".photo"), function() {
var imgsrc = $(this).attr("src").length;
console.log(imgsrc); // logging length it should now print the length
});
});
make sure to load this script first then your $.each() function:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
You are trying to read the lenght of an object / array out of context here :
var imgsrc = $(this).attr("src").length;
change to
var imgsrc = $(this).attr("src");
edit : in order to check if the attribute exists
if (imgsrc == undefined) { /* do something */ }

Can I use jQuery or javascript to make an <Img> behave like a link without the <a> based on class?

I have a large number of images of the same class "linkImg" and I would like them to behave as links without adding tags.
What I'm tryng is something like this:
<script type="text/javascript">
$(function()
{
$('.linkImg').click( function( event )
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
gotothelinl(linkPath, linkRel, linkTarget)// this is just a made-up function - it the part I don't know how to make work
})
} );
</script>
When it works it should behave like the tag was there with all attribute intact. I tried using location.href but I can't ad rel or target attributes to that.
thx in advance
David
To change the location of the page you'd do
location.href = "/newLocation.html"
This simulates a hyperlink (although I'm an ajax enthusiast!)
I think your are taking the problem for another angle... try this:
<script type="text/javascript">
$(function()
{
$('.linkImg').each( function()
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
$(this).wrap('<a href="'+ linkPath +'" target="' + linkTarget + '" rel="'+ linkRel + '" />')
})
} );
</script>

How to insert first image if no others selected

I am trying to figure out a way to insert the first image of a jquery gallery once it's loaded basically.
I've searched everywhere and can't seem to find anything. I have pasted the code that works so far below. I think I have to put something like:
$(function() {
$(".image").click(function() {
var image = $(this).attr("rel");
var title = $(this).attr("alt");
var description = $(this).attr("content");
$('#gallery').hide();
$('#gallery').fadeIn('slow');
$('#image').html('<img src="' + image + '"/>');
return false;
});
});
use .append
example
$(".image").click(function() {
var img = $('<img/>');
img.attr("src", $(this).attr("rel") );
var title = $(this).attr("alt");
var description = $(this).attr("content");
$("#gallery").append( img );
$('#gallery').fadeIn('slow');
return false;
});
This will also append other images once their respective links been clicked.

Categories

Resources