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

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";
}
}

Related

How to get ALT from IMG tag in JavaScript

I am using THIS script to display my galleries in lightbox. I was using some plugins but all of them does not display the alt=""(alt added in media in wordpress).
How can I modify the code from the link below to display the alt attributes ?
I found something in the code, but I dont know how to put the dynamic alt there(commented by uppercase text in the code). Dynamic I mean that as user will add the img in wordpress dashboard, he will put the alt then.
{
key: '_preloadImage',
value: function _preloadImage(src, $containerForImage) {
var _this4 = this;
$containerForImage = $containerForImage || false;
var img = new Image();
if ($containerForImage) {
(function () {
// if loading takes > 200ms show a loader
var loadingTimeout = setTimeout(function () {
$containerForImage.append(_this4._config.loadingMessage);
}, 200);
img.onload = function () {
if (loadingTimeout) clearTimeout(loadingTimeout);
loadingTimeout = null;
var image = $('<img />');
image.attr('src', img.src);
image.addClass('img-fluid');
image.attr('alt',"Temp TEXT"); // HERE I WOULD LIKE TO DISPLAY THE ALT AUTOMATICALLY - NOT STATIC AS IT IS NOW
// backward compatibility for bootstrap v3
image.css('width', '100%');
$containerForImage.html(image);
if (_this4._$modalArrows) _this4._$modalArrows.css('display', ''); // remove display to default to css property
_this4._resize(img.width, img.height);
_this4._toggleLoading(false);
return _this4._config.onContentLoaded.call(_this4);
};
img.onerror = function () {
_this4._toggleLoading(false);
return _this4._error(_this4._config.strings.fail + (' ' + src));
};
})();
}
img.src = src;
return img;
}
},
I am using wordpress on my page and my skills in JS are rather poor, so I am asking you :).
We don't really know what is the type of your img variable. If you want to set the alt tag of image to the one of img, simply do:
image.attr('alt', img.attr('alt'));
…if it's a jQuery object. Otherwise, if img is pure JavaScript, you can do:
image.attr('alt', img.alt);
if the img object holds the existing alt and image is the new jQuery object, then set it with jQuery
image.attr('alt', img.getAttribute('alt'))

How to have two fallback image placeholders

This works really well for filling a placeholder in place of an image that doesn't exist.
<img src="cantfind.jpg" onError="this.onerror=null;this.src='http://placehold.it/600x600?text=No Picture'">
What I was curious about is if there was a way to do two placeholders within the onError event. So I tried doing this but the Javascript isn't coming to me. any ideas? I tried assigning the urls to variable, but I'm not sure how to check for if the first placeholder fails without doing some messy xhr request or something.
Check if the current src equals one of the placeholders and assign a new url accordingly:
onerror="
var p1='http://.......', p2='http://......';
if (this.src == p1) this.src = p2; else if (this.src != p2) this.src = p1;
"
Here's one way of doing it via recursive event handling... try loading and if it errors, then try loading the first element from the array, and set it to error with the next index on failure, until you hit an index that is out of range, at which point stop.
This caters for any number of defined placeholders in the sources array.
<img id="img" src="example.jpg" onerror="loadNextImage(0);" alt="logo image">
<script>
var imagesDir = 'path/to/images/directory/';
var sources = [ '01.jpg', 'test.gif', 'bamf.jpg', 'foobar.jpg' ];
var index = 0;
function loadNextImage(index) {
var image = document.getElementById('img');
if (index < sources.length) {
console.log('Index:', index, sources[index]);
image.onerror = function() { loadNextImage(index + 1); };
image.src = imagesDir + sources[index];
} else {
image.alt = 'No suitable image found to display';
}
}
</script>

change the background image as you onmousemove on the different images javascript

function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
m.style.backgroundImage = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg')";
var p = document.getElementById('image');
p.innerHTML = previewPic.alt;
}
function unDo() {
/* In this function you should
1) Update the url for the background image of the div with the id = "image"
back to the orginal-image. You can use the css code to see what that original URL was
2) Change the text of the div with the id = "image"
back to the original text. You can use the html code to see what that original text was
*/
document.getElementById("image").style.backgroundImage = "url('')";
document.getElementById('image').innerHTML = "Hover over an image to display here";
}
I suspect this is homework thus I only give you a partial answer here:
function upDate(previewPic) {
/* In this function you should
1) change the url for the background image of the div with the id = "image"
to the source file of the preview image
2) Change the text of the div with the id = "image"
to the alt text of the preview image
*/
var m = document.getElementById("image");
// now how would I fix this string concatenation up? hmmm
m.style.backgroundImage = "url('" + previewPic.whattoplacehere +')";
// comment out as we have this var p = document.getElementById('image');
// change to m from p as we had it already.
m.innerHTML = previewPic.alt;
}
What event do we need? We need two it seems, what is the second one?
var myimage = document.getElementById("myimage");
myimage.addEventListener("mousesomething", function(event) {
var target = event.target,
related = event.relatedTarget;
upDate(what should be here?);
}, false);
Research:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
Use this in JS,
document.getElementById("demo").style.backgroungImage = url(" ") ;
Images in Html are already saved in src so, previewPic.src will be images link.
Don't forget to concatenation ..
like this "url" + "(" + parameters.src + ")" ;

Populate an input field with an image src in 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);
}

How can I re-render a specific element with backbone.js(or maybe do not need it) after whole page been loaded?

Say my page has loaded successfully.
There is an img element in the document like this:
<div class="pro_list_imgbox">
<img src="http://XXXX.com/bazinga.jpg" />
</div>
And I have backbone.js code like this:
events: {
'click .pro_list_imgbox': 'loadPic',
},
loadPic: function (e) {
var target = $(e.target),
pic = target[0].nodeName === 'IMG' ? target : target.find('img');
if (!pic.data('loadState')) {
pic.attr('src', pic[0].src += '?t' + new Date().getTime());
}
},
My question is how can I re-render this img element after I clicked it?
Will my loadPic function works? with a random num as suffix of src
And maybe something else I should do?
Looks like you're retrieving your image from a back-end controller, and that image is tagged according to the DateTime recorded upon retrieval.
To retrieve the same image, you'd have to save the source you used to retrieve that image. Given the code you already have, I'd say the most immediate answer would be to store the image source in the <img> element for the image, using $.data(), like this
loadPic: function (e) {
var target = $(e.target),
pic = target[0].nodeName === 'IMG' ? target : target.find('img');
if (!pic.data('loadState')) {
var picSource = pic[0].src += '?t' + new Date().getTime();
pic.data({ source: picSource });
pic.attr('src', picSource);
}
}
The <img> element that was clicked will now have the last source string for that image and can be recalled using
var imageSource = $('img-selector').data(source);

Categories

Resources