One of the WordPress plugins renders the uploaded image as a link:
news-paper.png
I want to convert it to an tag with JavaScript so that the link is displayed as an image
Not super familiar w/ Wordpress so there may be an easier way, but you could convert that link into an image by...
Changing the <a ... tag to an <image ... tag :
<image src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" target="_blank" aria-label="new"/>
adding an image via JS based off that value
function add_google_logo() { show_image("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png", 276,110, "Google Logo");
}
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
<button onclick="add_google_logo();">Add Google Logo</button>
^ completely ripped from this post: How to display image with JavaScript?
I'm working on a project where there are tiles of different pictures and I want to pass the value to another page when an image is clicked on. Since <img> doesn't have a value attribute, I tried to wrap an <a> tag around the image as follows, although it does the job, the format of the image is messed up. Is there a better way to do this that doesn't mess with the format of the image? Thank you for your help.
<a href="results.inc.php?value=gpu" onclick="post">
<img src="https://via.placeholder.com/200.jpg" alt="" class="cardImg">
</a>
Based on your comment, the most "harmless" way to do it would be JavaScript, adding a custom attribute to the image for the value you want it to pass in the onClick method.
document.addEventListener("DOMContentLoaded", function() {
var allCards = document.querySelectorAll(".cardImg");
for(i = 0; i < allCards.length; i++) {
var value = allCards[i].getAttribute("data-card-value");
allCards[i].addEventListener("click", function() {
document.location.href = "results.inc.php?value=" + value;
});
}
});
.cardImg {
cursor:pointer;
}
<img src="https://via.placeholder.com/200.jpg" data-card-value="gpu" alt="" class="cardImg">
Is there any way how to replace the path location using span or etc. that comes from the Jquery, or is there any shorcut in Django?, Currently as you can see I'm trying to override the path that comes from my jquery src="/media/<span id=image></span>". Is there any other way to pass the path image that comes from jquery into the img src?. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance
Jquery
$(document).on('click', 'a[data-role=show_scanned]', function(){
let csrf = $('input[name=csrfmiddlewaretoken]').val();
var path = $(this).attr('id'); #Image path example: image.jpg
var assign = $("#image").html(path);
$("#scanned_show").modal('show');
});
html retrieve
<img class="card-img img-fluid mb-1" src="/media/<span id=image></span>" alt="Card image cap" style="width: 900px;height: 600px;">
The line below can get the text of a span
$("#image").text()
You can then assign this to the src attribute of the img tag:
$("#imageDisplay").attr("src", $("#image").text() );
Demo:
// Add click event
$("#load").click(function() {
// Add text from span to src attribute of img
$("#imageDisplay").attr("src", $("#image").text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id=image>https://via.placeholder.com/150</span>
<button id="load">Load Image</button>
<img id="imageDisplay">
I am looking to contain my image sizes once they have been clicked on,
currently they are shown larger than I wish for them to appear.
Example: http://messaages.com/post/144951542174
HTML: https://gist.github.com/anonymous/4f09e3306f9b28ee0dce286342c51c7e
I have played around with various sizes within the code but I can't seem to be able to change it.
If you want to change the image sizes once they are clicked on you will want to use javascript to change the css.
<img onclick="imageChange(this)" style="width: 200px; cursor: pointer;" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
<script>
window.imageChange = function(image) {
if (image.style.width === "200px") {
image.style.width = "100px";
} else {
image.style.width = "200px";
}
}
</script>
JS Fiddle: https://jsfiddle.net/ws12fqzc/
If I have an image tag like the following:
<img src="myimage.jpg" />
and if I add "async" to it:
<img async src="myimage.jpg" />
will the image load asynchronous?
The way to async load (lazy load) the content is to not set the 'src' attribute and then execute a script that loads the images once DOM-ready is launched.
<img data-lazysrc='http://www.amazingjokes.com/images/20140902-amazingjokes-title.png'/>
and with jQuery (or possible with plain JavaScript too) use below code (as suggested here):
<script>
function ReLoadImages(){
$('img[data-lazysrc]').each( function(){
//* set the img src from data-src
$( this ).attr( 'src', $( this ).attr( 'data-lazysrc' ) );
}
);
}
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "interactive") { //or at "complete" if you want it to execute in the most last state of window.
ReLoadImages();
}
});
</script>
var img = new Image(),
url = "myimg.jpg",
container = document.getElementById("holder-div");
img.onload = function () { container.appendChild(img); };
img.src = url;
This would start loading an image as soon as you request it in-script, and whenever the image was done loading, it would grab and add the image to it.
There are lots of other ways of doing this...
This is just a dead-simple example of async loading of a single image.
But the moral is this:
For async loading to work, either load it in JavaScript and use the onload, or include the image tag on the page, without the src attribute (specify the width and height in HTML), and go back at some point, in JS, and set the image URL.
The modern way to do this is with the loading attribute for images and iframes.
Attribute: loading=lazy
This will defer loading of the content until the element reaches a calculated distance from the viewport (that just means, it's got quite likely that the user will scroll it into view).
<img src="defer.png" loading="lazy" alt="An Awesome Image" width="500" height="400">
Setting the attribute to lazy invokes the new behaviour.
This is already in Chromium since v76, but might not hit non-Chromium browsers until it goes through the usual specification shennanigans.
If you are going to defer loading using a script, it would be worth writing the image with the lazy attribute and polyfilling the behavior as opposed to working off of a class name, etc. That way, you can allow the native version to take over as it becomes available.
Forced Eager Loading
Automatic lazy loading may become a feature of lightweight browsing, in which case, you may want to do the inverse and force an image to load. You can use the same loading attribute with a value of eager to ask the browser to grab the image even if it might otherwise choose not to.
<img src="defer.png" loading="eager" alt="An Awesome Image" width="500" height="400">
Further reading
View the pull request for the WHATWG spec
Fallback JavaScript with notes about perhaps not using fallbacks
An alternate way to async load an image is by using Promise in javascript, which serves the purpose of doing things asynchronously.
function asyncImageLoader(url){
return new Promise( (resolve, reject) => {
var image = new Image()
image.src = url
image.onload = () => resolve(image)
image.onerror = () => reject(new Error('could not load image'))
})
}
// then use it like this
var image = asyncImageLoader(url)
image.then( res => {
console.log(res)
})
<img async src="myimage.jpg" />
The image tag doesnt supports any async attribute.
http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element
While several other answers highlight ways to fetch images asynchronously, it may also be helpful to know that the <img /> tag supports an attribute that serves as a hint to the browser that may result in images being be decoded asynchronously. It doesn't appear to be supported by Internet Explorer.
<img src="myimage.jpg" decoding="async"/>
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Img#attr-decoding
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/decoding
https://github.com/whatwg/html/issues/1920
If you're using jQuery, I did something simple, yet effective, like this:
HTML
<div data-lazy-load-image="/Images/image-name.png" data-image-classname="pop-in"></div>
JavaScript
$(function () {
$("[data-lazy-load-image]").each(function (index, element) {
var img = new Image();
img.src = $(element).data("lazy-load-image");
if (typeof $(element).data("image-classname" !== "undefined"))
img.className = $(element).data("image-classname");
$(element).append(img);
});
});
CSS
#-webkit-keyframes pop-in {
0% { opacity: 0; -webkit-transform: scale(0.5); }
100% { opacity: 1; -webkit-transform: scale(1); }
}
#-moz-keyframes pop-in {
0% { opacity: 0; -moz-transform: scale(0.5); }
100% { opacity: 1; -moz-transform: scale(1); }
}
#keyframes pop-in {
0% { opacity: 0; transform: scale(0.5); }
100% { opacity: 1; transform: scale(1); }
}
You could extend this to include additional optional attributes for each image, but you get the idea.
This will wait until the DOM is ready, then dynamically (async) load the images into the element that you mark with the data-lazy-load-image attribute. I included the CSS to make the images "pop in" when they are loaded.
While #Norguard's example is quite simple and easy enought for an image or two, I have found echo.js pretty handy for lazy-loading, https://github.com/toddmotto/echo.
It does lazy-loading images with data-* attributes and comes with some neat other things too.
<img data-echo="img/photo.jpg">
<script src="dist/echo.js"></script>
<script>
echo.init();
</script>
I have used the following approach with jQuery.
First, don't use a "src" attribute in the image tag, but put your source into a different attribute, like this:
<img async-src="/mydirectory/myimage.jpg" />
Then, within the jQuery document-ready function, I use this code to copy the element's async-src to the element's actual src:
$("img[async-src]").each(function(index) {
$(this).attr("src", $(this).attr("async-src"));
});
Notes:
jQuery's .each function may process the tags in the sequence they are coded in the HTML/DOM, but image sizes and network issues may mean that images don't actually load sequentially. In other words, your third async-src image might visually appear onscreen before the first has finished loading.
If your page layout relies on the pixel dimensions of that image file — e.g. you're not defining the image's dimensions via tag attributes, CSS, or a parent element — then you may have to use a "src" attribute on the original file pointing to a blank white or clear GIF of the dimensions you want.
Finally, if you want to process some code after the async loading of the image — for example, to handle a fading effect or change a CSS tag relevant to the element — expand the jQuery like this:
$("img[async-src]").each(function(index) {
$(this).load(function() {
// code to run after loading
});
$(this).attr("src", $(this).attr("async-src"));
});
It might be too late of an answer but recently was facing the same issue and the "lighthouse" in the console suggested that I should follow what's mentioned here in the link:
enter link description here
Basically, I did the following as suggested and it works really well:
<script src="lazysizes.min.js" async></script>
<!-- Images End -->
</body>
You may download the lazysizes.min.js from https://raw.githubusercontent.com/aFarkas/lazysizes/gh-pages/lazysizes.min.js
and source it locally.
Then, add the class lazyload to images that should be lazy loaded. In addition, change the src attribute to data-src.
For example:
<img data-src="images/flower3.png" class="lazyload" alt="">
You may be wondering why it is necessary to change the src attribute to data-src. If this attribute is not changed, all the images will load immediately instead of being lazy-loaded. data-src is not an attribute that the browser recognizes, so when it encounters an image tag with this attribute, it doesn't load the image. In this case, that is a good thing, because it then allows the lazysizes script to decide when the image should be loaded, rather than the browser.
Visit the reference for better understanding.
Hopefully it'll be of help to someone :)
You can read more about lazyload attribute:
<img src="myimage.jpg" alt="some description" lazyload/> - with default values
or you can prioritize:
<img src="myimage.jpg" alt="some description" lazyload="1"/>
<img src="myimage.jpg" alt="some description" lazyload="2"/>