Javascript - have text appear with an image when clicked on - javascript

I have just started with Javascript/HTML and am wondering how I could create a page that has say, 2 images on and when you click on an image text relevant to that image appears?
My images are listed as below:
<img class="thumb" data-ord="1" onclick='changeMainImg(this);' src="full/01.jpg">
My changeMainImg function:
function changeMainImg1(that) {
document.getElementById("fullview").src=that.src;
current=that;}
Can I implement the text in the function so that each of the two different images has its own text?
Thank you

There are several ways to achieve this. If text is short, you can add it as a dataset attribute in the same img tag like this:
<img class="thumb" data-ord="1" data-text="my text" onclick='changeMainImg(this);' src="full/01.jpg">
function changeMainImg1(that) {
document.getElementById("fullview").innerHTML = that.dataset.text;
}
Other way is to define a variable with all texts and call it by index:
<img class="thumb" data-ord="0" onclick='changeMainImg(this);' src="full/01.jpg">
var texts = [
'text 1',
'text 2'
];
function changeMainImg1(that) {
document.getElementById("fullview").innerHTML = texts[that.dataset.ord];
}

I assume displaying the src attribute works for you. Below a possible solution. Prerequisite is to assign the same class name to each image involved.
/* Store image elements in an array */
const images = [... document.getElementsByClassName('thumb')];
/* Assign event listener to each image element */
images.map( (image) => image.addEventListener( "click", function()
{ alert(image.src) }
));
<img class="thumb" data-ord="1" src="full/01.jpg">
<img class="thumb" data-ord="2" src="full/02.jpg">
<img class="thumb" data-ord="2" src="full/03.jpg">
<img class="thumb" data-ord="2" src="full/04.jpg">
<img class="thumb" data-ord="2" src="full/05.jpg">

Related

HTML - Img alt attribute hides image

I'm grabbing favicon's from sites programmatically by generically making a request for the icon to "example.com/favicon.ico".
If the site doesn't have a favicon, I want to use the "alt" attribute of the image to hide the image so that it doesn't appear and doesn't have a "missing image" icon.
For example
<img src="https://www.businessinsider.com/favicon.ico" alt="$(this).hide();" height="16" width="16">
Can this be done?
You can use the built-in error() method. Hide your image based upon that.
$("img").on("error", function() {
$(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.businessinsider.com/favicon.ico" height="16" width="16">
If you want an alternative image when the image is not available, give the new image source.
$("img").on("error", function() {
$(this).attr("src", "https://homepages.cae.wisc.edu/~ece533/images/mountain.png");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://www.businessinsider.com/favicon.ico" height="16" width="16">
You can put your placeholder immediately and check if the image loads on script. If it loads, replace the img src
var thisImage = new Image();
thisImage.src = 'https://www.businessinsider.com/favicon.ico';
thisImage.onload = function() {
console.log("Image 1 ready to append");
document.querySelector('.bg-image').src = thisImage.src;
};
<!--The source here is your placeholder-->
<img class="bg-image" src="https://placekitten.com/50/50" height="50" width="50" />

Display Image alt text using vanilla Javascript

I'd like to display the alt text for an image as a paragraph with a class using vanilla JavaScript.
Example:
<img src="image.jpg" alt="These are planets">
Rendered As:
<img src="image.jpg" alt="These are planets">
<p class="photo-caption">These are planets</p>
Try the following. Note that it uses es6 functions
const images = Array.from( document.querySelectorAll('img') );
images.forEach(image => {
let alt = image.getAttribute('alt');
if( alt )
{
image.insertAdjacentHTML('afterEnd', `<p class="caption">${alt}</p>`);
}
});
<img src="https://placeimg.com/240/280/any" alt="These are planets">
<img src="https://placeimg.com/240/280/any" alt="These are something">
<img src="https://placeimg.com/240/280/any" alt="Something else">
<img src="https://placeimg.com/240/280/any" alt="Something">
In case it's useful to anyone here's what I ended up with and it worked perfectly. This is useful if you'd like to selectively add captions to images without adding additional HTML to your Markdown:
Jekyll/Github pages markdown:
![These are planets](path/to/image.jpg){: .add-caption}
On build it will render:
<img class="add-caption" src="image.jpg" alt="These are planets">
Using #SuperDJ's JS
const images = Array.from( document.querySelectorAll('.add-caption') );
images.forEach(image => {
let alt = image.getAttribute('alt');
if( alt )
{image.insertAdjacentHTML('afterEnd', `<p class="photo-caption">${alt}</p>`);}
});
Final Output HTML:
<img class="add-caption" src="image.jpg" alt="These are planets">
<p class="photo-caption">These are planets</p>
Add CSS:
.photo-caption {
color: #999;
font-size: .5rem;
text-align:center;
}
Hope it's helpful to you. I searched the web for an hour and couldn't find a solution.

Get alt attribute of images inside a Contenteditable div and replace the image

I've implemented small web chat application and used smileys in it.
I've made my div contenteditable="plaintext-only" and adding both text and smileys images to that div.
whenever user clicks on smileys, an image with unicode character as alt will bind to the contenteditable div and he can also type text in it.
So, Finally after clicking the send button, I need to get the whole content in div and replace the images with unicodes in the alt and get the plain text as text itself and send message.
My smileys binding code :
$("span.emo", container).click(function () {
debugger;
var toSlice = $(this).attr("data-emoji").split('-'); // get unicode Character
var preview = emojione.toImage(toSlice[1]); // unicode to image conversion
$('.mydiv').html($('.mydiv').html() + preview); // append image to the div
});
My div's Content after adding images and text
<div id="mydiv" contenteditable="plaintext-only" class="mydiv" style="width: 100%; height: 100px; border: 1px solid #ccc; margin-bottom: 100px">
<img class="emojione" alt="πŸ‘Έ" src="//cdn.jsdelivr.net/emojione/assets/png/1F478.png?v=1.2.4"><img class="emojione" alt="😺" src="//cdn.jsdelivr.net/emojione/assets/png/1F63A.png?v=1.2.4">
<img class="emojione" alt="😸" src="//cdn.jsdelivr.net/emojione/assets/png/1F638.png?v=1.2.4"><img class="emojione" alt="😽" src="//cdn.jsdelivr.net/emojione/assets/png/1F63D.png?v=1.2.4">
<img class="emojione" alt="😼" src="//cdn.jsdelivr.net/emojione/assets/png/1F63C.png?v=1.2.4"><img class="emojione" alt="πŸ™€" src="//cdn.jsdelivr.net/emojione/assets/png/1F640.png?v=1.2.4"> Hello Users<br>
</div>
My Send Button Code
function Send() {
debugger;
//var allimgs = $('.mydiv').find('.emojione');
var alldata = $('.mydiv').html(); // getting all html data but dont know how to loop through every element
var childrendata = $(".mydiv").children(); // here I'm not getting the text, only getting the images as array
var contenteditable = document.querySelector('[contenteditable]'),
text = contenteditable.textContent; // here also I'm getting only text
}
My question is :
I need to get the data and loop through every element and replace all images with unicodes. My final data should be like : πŸ‘ΈπŸ˜ΈπŸ˜Ό Hello Users
You can iterate over children() and use replaceWith() to replace the img by its alt attribute.
function Send() {
$('.mydiv').children('.emojione').each(function () {
$(this).replaceWith($(this).prop('alt'))
});
}
Fiddle Demo
Add this little snippet for a demo transformation. It replaces images with their alt tag, pretty straight forward.
/* Added snippet */
window.transform = function() {
$('.emojione').each(function () { // for each emoji
var unicode = $(this).attr('alt'); // grab attribute 'alt'
this.outerHTML = unicode; // set the images entire html as the alt tag instead
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" contenteditable="plaintext-only" class="mydiv" style="width: 100%; height: 100px; border: 1px solid #ccc; margin-bottom: 50px">
<img class="emojione" alt="πŸ‘Έ" src="//cdn.jsdelivr.net/emojione/assets/png/1F478.png?v=1.2.4">
<img class="emojione" alt="😺" src="//cdn.jsdelivr.net/emojione/assets/png/1F63A.png?v=1.2.4">
<img class="emojione" alt="😸" src="//cdn.jsdelivr.net/emojione/assets/png/1F638.png?v=1.2.4">
<img class="emojione" alt="😽" src="//cdn.jsdelivr.net/emojione/assets/png/1F63D.png?v=1.2.4">
<img class="emojione" alt="😼" src="//cdn.jsdelivr.net/emojione/assets/png/1F63C.png?v=1.2.4">
<img class="emojione" alt="πŸ™€" src="//cdn.jsdelivr.net/emojione/assets/png/1F640.png?v=1.2.4"> Hello Users
</div>
<!-- Added Button -->
<button onclick="transform()">Transform!</button>

Adding an image via pure JS

I am new in JS,please help me.I have 4 images with the same class name and a hidden div which is displayed when one of 4 images is clicked. How i can add to my div the image which one is clicked? I do not want to write a function for every image.Is it possible with my code?
<img onClick="show()"class="img" src="css/images1/img1.png">
<img onClick="show()"class="img" src="css/images1/img2.png">
<img onClick="show()"class="img" src="css/images1/img3.png">
<img onClick="show()"class="img" src="css/images1/img4.png">
<div class="gallery"></div>
<script>
function show(){
var x=document.getElementsByClassName('gallery')[0];
x.style.display="block";
x.innerHTML='<img src=css/images1/img1.jpg>';
};
</script>
Pass in the "src" of the element that was clicked:
function show(src){
var x=document.getElementsByClassName('gallery')[0];
x.style.display="block";
x.innerHTML = '<img src="' + src + '">';
}
Then for your html <img/> tags pass in their src to show:
<img onClick="show(this.src)"class="img" src="css/images1/img1.png">
Edit: if you must select "gallery" by className, use getElementsByClassName as you originally had.

Jquery basic gallery animation

Ive made a basic "gallery" which uses the function below to show a larger picture when clicking on thumbnails. I want to make an animation to transition the thumbnail in to the bigger image. for example the thumbnail could slide to the place of the bigger image and spread to it or something along those lines.
function Kuvansuurennus(pic)
{
document.getElementById("peukalokuva").style.visibility="visible"
document.getElementById("peukalokuva").src=pic
}
Some style definitions I use
.thumb
{
height:150px;
width:200px;
}
#peukalokuva
{
float:right;
margin-right:4%;
width:70%;
visibility:hidden;
}
And the images I use and the target image for the bigger images
<img id="peukalokuva">
<div>
<img class="thumb" src="kuva1.jpg" onclick="Kuvansuurennus(this.src)"/>
<br>
<img class="thumb" src="kuva2.jpg" onclick="Kuvansuurennus(this.src)"/>
<br>
<img class="thumb" src="kuva3.jpg" onclick="Kuvansuurennus(this.src)"/>
<br>
<img class="thumb" src="kuva4.jpg" onclick="Kuvansuurennus(this.src)"/>
<br>
<img class="thumb" src="kuva5.jpg" onclick="Kuvansuurennus(this.src)"/>
<br>
<img class="thumb" src="kuva6.jpg" onclick="Kuvansuurennus(this.src)"/>
</div>
Thats the code, so how should I modify the funktion to get an animated transition from thumbnail to larger image?
You could do something with the format of...
$('img.thumb').click(function(){
var source = $(this).attr('src');
$('#peukalokuva').show().attr('src', source);
});
This would mean you wouldn't need click handlers in your html. You would want to reference a larger image though. Possibly in a different folder. source = 'large/' + $(this).attr('src')

Categories