I'd like to use a large background image for desktop users and a different smaller background image for mobile users.
I found this answer
.img-responsive.mobile {
display: none;
}
#media only screen and (max-device-width: 480px) {
.img-responsive {
display: none;
}
.img-responsive.mobile {
display: block;
}
}
<div class="row">
<img src="image\bannerimages\Career.png" class="img-responsive careerpage">
<img src="image\bannerimages\Career-mobile.png" class="img-responsive careerpage mobile">
<h2 class="careerbannertext">LIFE AT TEKNOTRAIT</h2>
...
</div>
how-to-display-different-images-in-mobile-and-desktop-devices
Problem with this solution is it loads two images - I'd like to only load the image necessary. How can this be done?
Using pure Javascript
javascript:
<script>
var screenWidth = screen.width;
var imgElement = document.createElement("img");
var imgUrl;
if(screenWidth < 480) {
// for mobile devices
imgUrl = document.createTextNode("url of img 1");
} else {
// otherwise
imgUrl = document.createTextNode("url of img 2");
}
var row = document.getElementByClassName("row");
row.insertBefore(imgElement, row.childNodes[0]);
</script>
html:
<div class="row">
<h2 class="careerbannertext">LIFE AT TEKNOTRAIT</h2>
...
</div>
I think html code is crystal clear so I just describe javascript code. first of all gets width of screen then checks whether it is a mobile device or others. then inserts url of proper image in created element and finally inserts it as the first element of div.row element.
Also you can do this easier using jQuery.
<div class="row">
<img id="img1" src="image\bannerimages\Career.png" class="img-responsive careerpage">
<img id="img2" src="image\bannerimages\Career-mobile.png" class="img-responsive careerpage mobile">
<h2 class="careerbannertext">LIFE AT TEKNOTRAIT</h2>
...
</div>
var w = window;
var x = w.innerWidth;
if(x<568){
document.getElementsById('img2');
}
else{
document.getElementsById('img1');
}
Not sure without a full syntax, try this way Hope it works)
Related
Is it possible to resize an image coming from an API call? I am extracting an image from an API and trying to insert into a div on the page. The API is "NASA image of the day" and its a new image from nasa each day. Sometimes the image is vertical, and sometimes the image is horizontal depending on the day. What is the best way to handle this situation? I don't want the image to exceed the div it is inside of (40rem x 40rem), and right now the image posts really big on the screen and isn't contained inside of the div at all.
HTML:
<section class="section" id="section--1">
<div class="section__title">
<div class="title--info">
<h2 class="section__description">Image of the day <button>view</button></h2>
<h3 class="section__header">
View the "image of the day" taken by NASA satellites in space
</h3>
</div>
</div>
<div class="parent__el"></div>
<!-- <figure class="space__photo">
<img src="/img/space.jpg" alt=""/>
</figure> -->
CSS:
.parent__el {
height: 40rem;
width: 40rem;
margin: 0 auto;
}
JavaScript:
const imageContainer = document.querySelector('.parent__el')
const loadImage = async function() {
try {
// 1) loading recipe
const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=BSw3P3LRHk0brFlI5xMlVkaTdwUZuA3arh0A5ziV');
const data = await res.json();
if(!res.ok) throw new Error(`${data.message} (${res.status})`);
console.log(data)
// 2) rendering recipe
const markup = `
<div class="space__photo">
<img src="${data.url}" alt="" />
</div>
`;
imageContainer.innerHTML = markup;
} catch(err) {
alert(err)
}
}
loadImage()
You could also try setting the image as the background image of your space_photo container:
const markup = `
<div class="space__photo" style="background-image: url('${data.url}'); background-size:cover;">
</div>
`;
You would then have to give the class "space__photo" an appropriate size though (height and width 100% for example, so it stretches the entire length of your parent_el)
give your image an id, "img".
in your div rendering part, do this:
let img = document.getElementById("img")
if(img.style.height >= img.style.width) {
img.style.height = '40px'
} else {
img.style.width = '40px'
}
This makes it so when the image is verticle, it renders it as 40px height. When it is horizontal, it is 40px width.
I'm working on a meme editor website using the html2canvas library from https://html2canvas.hertzen.com/
here is my html code for the div that I need to capture:
<div class="container">
<div id="theUserMeme">
<div class="row">
<p id="memeWords">
When I see something lol
</p>
</div>
<div class="row">
<img id = "memeImage" src="images/init meme.jpg">
</div>
</div>
</div>
Also, this my JavaScript code that I run to capture the div:
function generateMeme(){
window.scrollTo(0,0);
html2canvas(document.querySelector("#theUserMeme")).then(canvas => {
var image = canvas.toDataURL('image/jpeg', 1);
console.log(image);
alert(image);
document.getElementById("finalImageCopy").src = image;
});
}
After hosting the code on Github, I tried the page on my iPhone and my laptop. It was working well on both devices, but after that it is working on the phone only. When I use it on the desktop, the captured image isn't full and sometimes it is only white image.
What is the problem could be?
It seems by default width of a <div> is equal to width of the visible area (please correctly if I'm wrong) and if an image is larger it doesn't "stretch" the div, it simply overflows out of it
So one way to fix this is to add width: fit-content; to your element:
https://jsfiddle.net/vanowm/h5yroe2q/
function generateMeme(id, options){
window.scrollTo(0,0);
html2canvas(document.querySelector("#theUserMeme"), options).then(canvas => {
console.log(canvas);
var image = canvas.toDataURL('image/jpeg', 1);
console.log(image);
document.getElementById(id || "finalImageCopy").src = image;
});
}
//generate first image
generateMeme();
//generate second image with adding options to html2canvas
generateMeme("finalImageCopy2", {
width: document.querySelector("#theUserMeme").scrollWidth
});
//set width
document.querySelector("#theUserMeme").style.width = "fit-content";
//generate third image
generateMeme("finalImageCopy3");
body
{
width: 50px;
}
pre
{
width: fit-content;
}
pre > img
{
border: 2px solid red;
}
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<div class="container">
<div id="theUserMeme">
<div class="row">
<p id="memeWords">
When I see something lol
</p>
</div>
<div class="row">
<img id = "memeImage" src="data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEABALDBoYFhoaGRodHRofIh8iIB0iHSUfJR8dLigyMC0nLS00PVBCNDhLOSstRWFFS1NWW1xbMkFlbWRYbFBZW1cBERISGBYZLRcaLVc2NTZXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dXV//AABEIAMgBLAMBEQACEQEDEQH/xAAaAAEBAQEBAQEAAAAAAAAAAAAAAQIEAwUG/8QAOxAAAgIAAwQFCQYHAQEAAAAAAAECEQMhMQQSQVEFImFxkRMUFTJTgZKh0UJyscHh8AYjM0NSYsKCsv/EABkBAQEBAQEBAAAAAAAAAAAAAAABAgMEBf/EACQRAQEBAAIBBQADAQEBAAAAAAARAQISEwMhMVFhFCJBQjIj/9oADAMBAAIRAxEAPwDJ9Z8ZAAFAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKQAIAA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ko+jckt75Dz59FWXR9v1+XAefPoqro/O973UPPn0VF0fr1+HIef8KR6Oy9f5E8+fRR9G5Lr/Ief8KPo5Zdd6ch5/wr0hsKUlJS43oZ5etckHWmjgGXgQSkVEpcgL7gCAjlXzAXy8Cgr4agbz40QRt2Afa9QJvfvQBdr9QIrYFsDSfz0yAm88skwKtSBfYAUuzjzAAE70KDtfvQCZ8suQEt60Abb4AbUXXayCacAIu4oZ8OIBNMBxqsgJbvSgKlnoBFl2/UDSXNfMgjb5UUZefDICrwAmi0AqAgBx42yi5eICKXDvse4u7V/MCPh4kF8Hp3gGuYC0l+8gMqSRYLGfZx4Eg0pdogb2eYB9nKwG9l+YGZSqtedjMGfOF77a9xeoqxdbV93IdRpSyuiQai7+fEgKarIQSUkv3xKI5JagVOq49gGd7P5iCqaf748hAlPXL6CAn2aAZU89M/xLAjip6cf39BBVPOtSQPKIQN/LXmBV+7Ayn29nvEFbQByV0nnyAliCNp8Sj/2Q==">
</div>
</div>
</div>
<pre>
Captured image:
<img id="finalImageCopy">
Captured image manually set canvas width:
<img id="finalImageCopy2">
Captured image with <b>width: fit-content</b>:
<img id="finalImageCopy3">
</pre>
In a DIV I have inserted images that I always want to display in 60% width of the original size of the image file (so that the images are on the same scale). For this I use the following jQuery-Script:
var cont_slider_ori_width;
var cont_slider_ori_height;
$('.img-drawing').each(function(i) {
var img = $(this);
$("<img>").attr("src", $(img).attr("src")).load(function() {
cont_slider_ori_width = this.width; // to get the original width of the image-file
cont_slider_ori_height = this.height; // to get the original height of the image-file
});
img.width(cont_slider_ori_width * 0.6);
// alert($(this).attr('src')); // If I avtivate this alert command, the size-changes work as it should ...
});
The HTML-Markup:
<div class="cont-slider-item-img-wrapper">
<div class="cont-slider-item-drw">
<img class="img-drawing" src="image1.png" alt="" width="1042" height="412">
</div>
<div class="cont-slider-item-drw">
<img class="img-drawing" src="image2.png" alt="" width="1042" height="411">
</div>
</div>
SCSS:
.cont-slider-item-img-wrapper {
display: flex;
justify-content: center;
.cont-slider-item-drw {
img {
width: auto;
height: auto;
}
}
}
But unfortunately this does not work (the size is not changed). It's strange that when I activate the 'alert' command, the redraw for the respective elements works as expected after each confirmation of the alarm box.
What did I do wrong? Thanks in advance for any help!!
With the friendly help of Chris G (see comments above) I was able to solve the problem. This is the jQuery/Javascript code, which is working now:
var cont_slider_ori_width;
var cont_slider_ori_height;
$('.img-drawing').each(function(i) {
cont_slider_ori_width = $(this).get()[0].naturalWidth;
$(this).width(cont_slider_ori_width * 0.6);
});
I want to hide all images which have no data-web-src attribute on 767px. I tried the following but I failed; how can I do that?
$('#homepage-carousel .lazy_res').each(function(index, value) {
var ws = $(window).width();
var large = 1024;
var medium = 767;
var small = 0;
if (ws <= medium) {
$(this).not('[data-web-src]').hide();
} else {
$(this).not('[data-web-src]').show();
}
});
img {
width: 500px;
float: left;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="homepage-carousel">
<img class="lazy_res" src="http://pre07.deviantart.net/338a/th/pre/i/2012/007/f/7/mapa_mundi_com_bandeiras___preto_by_plamber-d4leocd.jpg" alt="" />
<img class="lazy_res" src="http://img05.deviantart.net/a6be/i/2013/099/8/9/helena_harper_by_plamber-d6125tx.jpg">
</div>
Codepen Demo
This should be done with CSS Media Queries. No JavaScript required.
/* Set page default styles and styles that should only
be in effect for viewports under 767px wide here. */
img {
width: 500px;
float: left;
margin-right: 10px;
}
/* Apply the following CSS only to viewports wider than 767px */
#media (min-width: 767px) {
/* Select all images except those with an attribute of: dat-web-src */
img:not([data-web-src]) {
display: none; /* Hide the matching elements */
}
/* Make any other CSS changes you like here */
/* This class will only be applied to images when the media query
is in effect. */
img.someNewClass {
/* Whatever you need here */
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="homepage-carousel">
<img class="lazy_res" src="http://localhost:82/works/anitur/img/slider/1.jpg" alt="" />
<img class="lazy_res" src="http://localhost:82/works/anitur/img/assets/mice-1.jpg">
</div>
You need to set your code within a function and then it can be called onload and also onresize to test it:
see https://api.jquery.com/on/
Description: Attach an event handler function for one or more events to the selected elements.
function testit() {
$("#homepage-carousel .lazy_res").each(function(index, value) {
var ws = $(window).width();
var large = 1024;
var medium = 767;
var small = 0;
if (ws <= medium) {
$(this).not('[data-web-src]').hide();
} else {
$(this).not('[data-web-src]').show();
}
});
}
$(window).on('resize load', testit );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
below 767px wide, you'll see nothing else here :), use the full page mode to test the snippet. then resize the window
<div id="homepage-carousel">
<img class="lazy_res" src="http://pre07.deviantart.net/338a/th/pre/i/2012/007/f/7/mapa_mundi_com_bandeiras___preto_by_plamber-d4leocd.jpg" alt="" />
<img class="lazy_res" src="http://img05.deviantart.net/a6be/i/2013/099/8/9/helena_harper_by_plamber-d6125tx.jpg">
</div>
https://codepen.io/gc-nomade/pen/EXLZEN
I'm trying to set up a simple gallery with thumbnails and a main content section. When a thumbnail is clicked, I would like a larger version of the image along with text to display in the main content section. I've got the code for the images down, but can't figure out how to add text on each click. I haven't started doing any styling yet, but the basic code is below. Any help would be much appreciated.
Thanks!
JavaScript:
var mainImg = document.getElementById('Main');
document.getElementById('One').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297';
mainImg.innerHTML = imagetitle;
//alert('one clicked');
};
document.getElementById('Two').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297';
mainImg.innerHTML = 'imagetitle';
//alert('two clicked');
};
document.getElementById('Three').onclick = function() {
mainImg.src = 'http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297';
//alert('two clicked');
};
CSS:
#One, #Two, #Three {
width:100px;
opacity: .5; /* css standard */
filter: alpha(opacity=50); /* internet explorer */
}
#One:hover, #Two:hover, #Three:hover {
width:100px;
opacity: 1; /* css standard */
filter: alpha(opacity=100); /* internet explorer */
}
HTML:
<img id="Main" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<img id="One" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<img id="Two" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="" />
<img id="Three" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="" />
http://jsfiddle.net/f9B8H/72/
Let's clean this up a bit.
HTML
<div id="container">
<img id="Main" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" />
<p id="caption"></p>
</div>
<img id="One" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="I'm a soldier" />
<img id="Two" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="My family" />
<img id="Three" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="Dad" />
Notice how I've stored the caption in the alt attribute. A data attribute could also work.
JAVASCRIPT
function displayImage() {
var mainImg = document.getElementById('Main');
var caption = document.getElementById('caption');
mainImg.src = this.src;
caption.innerHTML = this.alt;
}
document.getElementById('One').onclick = displayImage;
document.getElementById('Two').onclick = displayImage;
document.getElementById('Three').onclick = displayImage;
Fiddle: http://jsfiddle.net/g2hY4/
The simplified function works so well because you are using the same image for thumbnail as main image. If you didn't do that, we could store the big image address in a data attribute also.
Here's one way to load the first caption when the page loads. Put it after the code I've already shown you:
displayImage.call(document.getElementById('One') );
You can read about call here. In a nutshell, it redefines the value of this in the displayImage function.
New fiddle
Something to think about is where you want the caption and how it's styled can be set in CSS. I've left that to you also. Absolute positioning will work if the positioning of #container is set to relative.
My implementation gets the text from the attribute alt(could be title) I think this way can be more elegant
document.getElementById('textSubtitle').innerHTML = this.alt;
http://jsfiddle.net/WKfc5/
If you are okay with using jQuery, here is something that I made up real quick. I hope it is useful. [Fiddle]
HTML
<div id="gallery">
<div class="preview">
<img class="previewImg" src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" title="" />
<div class="previewText"></div>
</div>
<div class="thumbnails">
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Kaylee_Radzyminski.jpg?7297" alt="" title="Image 1" />
</a>
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Mason_Hunter_Thornal.jpg?7297" alt="" title="Image 2" />
</a>
<a href="javascript: void(0);">
<img src="http://cdn.shopify.com/s/files/1/0176/5914/files/Joseph_Nunez_4afb23ac-d71e-42a0-9366-ac78d65deaf4.jpg?7297" alt="" title="Image 3" />
</a>
</div>
</div>
CSS
#gallery {
overflow: hidden;
}
#gallery .preview {
float: left;
position: relative;
}
#gallery .previewImg {}
#gallery .previewText {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 100px;
background: rgba(0,0,0,0.7);
color: #fff;
font: normal 12px arial;
padding: 10px;
}
#gallery .thumbnails {
float: left;
width:100px;
}
#gallery .thumbnails a, #gallery .thumbnails img {
display: block;
}
#gallery .thumbnails a img {
width: 100%;
opacity: .5; /* css standard */
filter: alpha(opacity=50); /* internet explorer */
}
#gallery .thumbnails a:hover img {
opacity: 1; /* css standard */
filter: alpha(opacity=100); /* internet explorer */
}
JS
$(function(){
var gallery = $("#gallery"),
thumbnails = gallery.find(".thumbnails a"),
previewImg = gallery.find(".previewImg"),
previewText = gallery.find(".previewText");
thumbnails.on("click", function(e){
var thumbImg = $(this).find("img");
previewImg.attr("src", thumbImg[0].src);
previewText.html(thumbImg[0].title);
});
});
I'd call the onclick from the image itself instead of adding the onclick via JS to the image.
You're doubling your work.
Where do you want the text to be displayed?
If it has to be displayed on top of the image, you'll have to make the image a background-image of a div or so.
If the text has to be above/under the image, place a span above/under the image and give it an ID.
Working with a span
JS:
function showBig(srcBig, title) {
var mainImg = document.getElementById('MainImg');
var mainText = document.getElementById('MainText');
mainImg.src = srcBig;
mainImg.title = title;
mainText.innerHTML = title;
}
HTML:
<div id="main">
<span id="MainText">Title will come here</span>
<img src="Default Img" alt="Big img's will come here" />
</div>
<img src="URL of thumbnail (e.g. smaller version)" alt="" onClick="showBig('URL of big version', 'Title')" />
Working with BG-image
JS:
function showBig(srcBig, title) {
var mainDiv = document.getElementById('MainDiv');
MainDiv.style.backgroundImage = srcBig;
MainDiv.innerHTML = title;
}
HTML:
<div id="MainDiv">
</div>
<img src="URL of thumbnail (e.g. smaller version)" alt="" onClick="showBig('URL of big version', 'Title')" />
By the way, you can ofc still add the onClicks via JS:
document.getElementById("yourImg").onclick = showBig('URL of Big', 'Title');
By the way, Don't use the same img for the thumbnails.
You'll probably use some big images which takes longer to load and then display it much smaller via CSS.
Make a smaller version (e.g. 100x100px or whatever size the thumbs should be) and only load the bigger version when the onClick is called.
Also, you better use a CSS-class like .thumbs to style the thumbs.
Otherwise you'll have to add a new ID to the list in your CSS file everytime you add a new image.
JSFiddle