JavaScript tasks - javascript

I have been learning JavaScript and I have been doing some tasks, which I got in my college.
Tasks go like this:
Make a webpage, where 3 200x150 images and one 600x450 image will appear. Add JavaScript function, which will make sure, that the 600x450 image shown will be an enlarged image of an 200x150 image, on which we have pointed with a mouse previously (call the function with onMouseOver).
The second task goes like this:
Complete the webpage from task 1 in a way, when clicking the smaller image, the bigger image of the same image, we clicked will appear in a new window.
The code for the 1st task looks like this:
function bigImg(x)
{
x.style.height="600px";
x.style.width="450px";
}
function normalImg(x)
{
x.style.height="200px";
x.style.width="150px";
}
...
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="slika1.jpg" alt="slika1" width="150" height="200">
<img src="slika2.jpg">
<img src="slika3.jpg">
For the 2nd one like this:
function swipe()
{
var largeImage = document.getElementById('Slika1');
largeImage.style.display = 'block';
largeImage.style.width=450+"px";
// enter code here
var url=largeImage.getAttribute('src');
window.open(url,'Image','width=largeImage.style.width,height=largeImage.style.height,resizable=1');
}
...
<img src="slika1.jpg" id= "Slika1" onClick="swipe();"/>
<img src="slika2.jpg">
<img src="slika3.jpg">
What should be done differently?

<script>
function swipe(image)
{
newWidth=450+"px";
newHeight=600+"px";
var url=image.getAttribute('src');
myWindow=window.open('','Image','width='+newWidth+',height='+newHeight+',resizable=1');
myWindow.document.write('<img src="'+url+'" width="'+newWidth+'" height="'+newHeight+'" />');
}
</script>
<img src="slika1.jpg" onClick="swipe(this);"/>
<img src="slika2.jpg" onClick="swipe(this);"/>
<img src="slika3.jpg" onClick="swipe(this);"/>
To answer a few questions of the original poster:
The first parameter in the window.open() function here is '' (empty string), which basically creates a blank web page. The return value of this function call is the newly opened web page (which is assigned to the variable myWindow). You then drill down into that window object and call it's document.write() function to actually display the desired HTML (the image). In your original code you were simply opening a window that browsed to the image file (not an HTML page). Since that was the case, there is no way you could have actually set the width or height of the image--you were just setting (or trying to) the width and height of the window. Setting the width and height of the window wasn't even working in your example code because you didn't break the variable out of the string. So in the window.open() function you needed to pass a string in the third parameter that looked like:
width=450px,height=600px,resize=1
But what you were actually passing was:
width=largeImage.style.width,height=largeImage.style.height,resizable=1
The swipe() function we created takes in a single parameter "image". When we call this function from the onClick event inside the img tag we use the keyword "this" to pass a reference of itself. Essentially a copy of the img object that called swipe() is passed in as a parameter. So in the function, image.getAttribute('src') references the "src" attribute of the img object that called it, which you need to display in the opened window.

Related

Javascript: Using onmouseover and onmouseout functions on more than one image

Edit: Sorry if I reply late to any solutions because I need time to figure out how they work haha
I am a beginner in Javascript and I am currently trying to use this piece of code to change an image on mouseover
// Mouseover change (Ciel):
function rollover(my_image){
my_image.src = "images/ci2_a.png";
}
function mouseaway(my_image){
my_image.src = "images/ci_a.png";
}
and this is the corresponding HTML
<img src="images/ci_a.png" onmouseover="rollover(this)" onmouseout="mouseaway(this)" alt="xxx" style="float:left; width:38%">
This works fine, but I want to do it for more than one image on the same page (a different image rollover for each picture) . Even after changing the name of the functions and stuff it doesn't work. The first image stops changing onmouseover immediately when I try to add a similar function for the next image. Could someone tell me how to perform similar events on more than one image (not concurrently)? Thank you!
You could add event listeners to all the image elements you'd like.
<img class="my-image" src="images/ci_a.png" onmouseover="rollover(this)" onmouseout="mouseaway(this)" alt="xxx" style="float:left; width:38%"/>
function rollover(){
this.src = "images/ci2_a.png";
}
function mouseaway(){
this.src = "images/ci_a.png";
}
const myImages = document.querySelectorAll('.my-image')
myImages.forEach(img => {
img.addEventListener('mouseenter', rollover)
img.addEventListener('mouseleave', mouseaway)
})
You can send the image file as the second parameter like this:
function rollover(element, image) {
element.src = image
}
...
<img onmouseover="rollover(this, 'images/ci2_a.png')" ...>
But my question is why do you need JavaScript for that? You can use a simple CSS to achieve this.
Since you need different images on load and on hover, you need a single way to define this functionality across a collection of images.
Building on Matthew's approach, here's a way to do that.
JSFiddle to test it real-time.
You'll dynamically generate the images using data attributes to store the alternate (hover) image URL.
<img class="pics" src="https://picsum.photos/id/0/100"
data-swap="https://picsum.photos/id/10/100">
<br>
<img class="pics" src="https://picsum.photos/id/1/100"
data-swap="https://picsum.photos/id/11/100">
<br>
<img class="pics" src="https://picsum.photos/id/2/100"
data-swap="https://picsum.photos/id/12/100">
<br>
<img class="pics" src="https://picsum.photos/id/3/100"
data-swap="https://picsum.photos/id/14/100">
Then define the event listeners for all elements with the class pics. Here's a list of all the events that can be referenced.
On mouseover, store the original image in a data element original.
Then change the src with the value of the data-swap.
On mouseout, replace the src with the original value.
const myImages = document.querySelectorAll('.pics')
myImages.forEach(img => {
img.addEventListener('mouseover', function () {
img.dataset.original = img.src;
img.src = img.dataset.swap;
});
img.addEventListener('mouseout', function () {
img.src = img.dataset.original;
});
})

Why does onload cause my image switch to flicker?

For some reason, when I use the attribute onload on my img tag, it causes my images to flicker. Ideally, when I load the page, an image is displayed and when I refresh the page, the image is changed.
Here's my tag as well as the function for it:
HTML
<img id="randomimage" onload="randomImg()" src="images/carmainpic.jpg" alt="main pic of car"/>
JavasScript
function randomImg(){
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
Because the function you're calling changes the image's src to a random pick from the array, triggering a new load event, which changes the src randomly again, etc. On at least some browsers the cycle probably stops when you happen to assign the URL the image already has, too.
If your goal is to just show one of those images, at random, you can do that by leaving src off the img entirely and then adding it (once) with script (either immediately following the img in order to avoid your layout having to be adjusted when you add it, or in script at the end of the page if you prefer; no need to wait for any event):
<img id="randomimage" alt="main pic of car"/>
<script>
(function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random() * images.length); // <== Note change, so adding images to the array Just Works
document.getElementById("randomimage").src=images[num];
})();
</script>
Even if you put the script immediately after the <img ...> tag, the img element will be available to the script. So your choice whether to do it inline or with the other scripts at the end of the page.
The randomImg function is called every time the image loads. You can use a flag variable to make sure that you only change the image once:
var changed = false;
function randomImg(){
if (!changed) {
changed = true;
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
}
The problem is that you are listening to the load event on the image, instead of the page.
onload="randomImg()"
So, as soon as the first image loads, it triggers the function randomImg which causes change of src attribute on the image. So the browser will attempt to assign a new image to the element, and yet another load event is triggered, which repeats the entire cycle.
Instead, if you want to choose a random image when the page loads, you can listen to DOMContentLoaded event on the document, and choose a random image.
document.addEventListener("DOMContentLoaded", function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
console.log("Showing: " + images[num]);
});
<img id="randomimage" src="images/carmainpic.jpg" alt="main pic of car"/>
Note: Since you are selecting a random image, it is not guaranteed that you will always get a different image when the page is refreshed. Instead, if you must get a different image on refreshing the page, you can perhaps persist the image identifier in localStorage, and use that to determine the next image to display.
Well you can use $(document).ready(function(){}) to do that. Because you want when charge the page that function execute it.
$(document).ready(function(){
function randomImg(){
var images=["https://www.bensound.com/bensound-img/romantic.jpg","https://www.psdstack.com/wp-content/uploads/2016/10/featured-copyright-free-mages.jpg","http://shaebaxter.com/wp-content/uploads/2015/04/Life-of-Pix-free-stock-photos-sea-peaople-water-waves-back-Sunset-Joshua-earle-1024x682.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
randomImg();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="randomimage" src="" alt="main pic of car"/>

JavaScript - Changing preview image by clicking a thumbnail image with addEventListener only

I'm trying to create a very simple, pure JavaScript image gallery where upon clicking on a smaller image thumbnail, it changes the larger preview image to the thumbnail you just clicked.
I'm new to JavaScript and i've been experimenting with it a bit. I'm also trying to avoid using onClick within the HTML as I've been told that's bad practice. So I've found that using the addEventListener seems to be another approach.
The only problem is, that i'm not sure what to do with it. Most of the other tutorials use the onClick function which isn't ideal.
I was wondering if anyone could help or even provide some other sources to give me a start.
Here is the HTML and my start at the JavaScript:
HTML
<section class="image-gallery">
<h4>IMAGE GALLERY</h4>
<section id="gallery-preview">
<img src="images/gallery1.png" alt="image-gallery-1">
</section>
<section id="gallery-thumbnails">
<img src="images/gallery1.png" alt="image-gallery-1">
<img src="images/gallery2.png" alt="image-gallery-2">
<img src="images/gallery3.png" alt="image-gallery-3">
<img src="images/gallery4.png" alt="image-gallery-4">
<img src="images/gallery5.png" alt="image-gallery-5">
</section>
</section>
JavaScript
(function(){
let image-preview = document.getElementById("gallery-preview");
let image-thumbnail = document.getElementById("gallery-thumbnails");
image-thumbnail.addEventListener("click", imageChanger);
function imageChanger()
{
//something here
}
})();
Don't use hyphens in your JavaScript variable names. The dash is for subtraction. You can use dashes in class names and element id's, but not as JavaScript variable names.
Your html needs a class for all your images.
<section id="gallery-thumbnails">
<img class="my-images" src="images/gallery1.png" alt="image-gallery-1">
<img class="my-images" src="images/gallery2.png" alt="image-gallery-2">
<img class="my-images" src="images/gallery3.png" alt="image-gallery-3">
<img class="my-images" src="images/gallery4.png" alt="image-gallery-4">
<img class="my-images" src="images/gallery5.png" alt="image-gallery-5">
</section>
Next, your JavaScript runs asynchronously. You need to understand that. It means that you should not attempt to run your "imageChanger()" function until all the html is loaded. If the html is still loading, some of it might not be present when your function tries to attach the eventListener to it.
By asynchronous, it means JavaScript runs and doesn't wait around for long processes to finish before executing the next line of code. You can do quick things, like add a couple of numbers, but when you are grabbing data from a server and presenting it in html pages, these things take time. You need to be sure you work on them only after they are ready.
To ensure the html is loaded, look into jquery's $(document).ready() {}. You will need to include Jquery with a <script> tag to use it.
$(document).ready() {
let myImages = document.getElementsByClassName("my-image");
// You have more than one image in myImages.
for (i = 0; i < myImages.length; i++) {
myImages.addEventListener("click", imageChanger);
}
}
// Notice this function is **outside** of document.ready.
// You need the function immediately available.
function imageChanger()
{
// "this" is the element you clicked.
this.style.height = 100px;
this.style.width = 100px;
}
(function(){
let imagePreview = document.querySelector("#gallery-preview img");
let imageThumbnail = document.getElementById("gallery-thumbnails");
imageThumbnail.addEventListener("click", imageChanger);
function imageChanger(e) {
imagePreview.src = e.target.src;
}
})();

JavaScript - onclick image change using 'if'

I tried js image changing example using two different if methods.
<img id="myImage" onclick="changeImage()" src="s.png">
Click image
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.getAttribute('src')=='s.png')
image.src="m.png";
else
image.src="s.png";
}
</script>
Above method works totally fine no matter how many times clicked on the image or no matter which image is compared inside the 'if' part.
But below method which is given in w3c doesn't work as expected.
function changeImage(){
var image = document.getElementById('myImage');
if (image.src.match("s"))
{image.src ="m.png";}
else
{image.src ="s.png";}
This second method works only at first click. And also when the image compared inside the 'if' part is swapped with other image, it doesn't work at all even at the first click. Can someone please explain me, why second 'if' method doesn't work properly while first 'if' method works finely?
The reason why your code is not working is that web browser automatically adds site path to your image url because you are using relative image url. So you will have 's' character in every url (because s letter is in site url). And every .match('s') will always return true.
The solution is just to find out another checking of current image.
Here is example which logs out image src, so it should help you to understand the problem: https://jsfiddle.net/0yL0fwpL/4/
Html:
<img id="myImage" onclick="changeImage();" src="s.png">
Click image
Javascript:
changeImage = function() {
var image = document.getElementById('myImage');
if (image.getAttribute('src')=='s.png') {
image.setAttribute('src', "m.png");
} else {
image.setAttribute('src', "s.png");
}
}
Working example: https://jsfiddle.net/0yL0fwpL/2/

How can I pass my dynamically-generated variable to the function inside the innerHTML of a javascript function?

On my site, I use an onclick event on a link to call a javascript function (links are located within a WHILE loop from an external php file). The onclick from within the php WHILE loop passes the user picture and a username to a javascript function called ShowUser(). The event correctly generates a username and photo and places it within the innerHTML of a div as follows:
<script language="javascript" type="text/javascript">
function ShowUser(userpic,username) {
var TitleDesc1 = 'Click this photo to learn more about '+username+'';
document.getElementById('UserPicHolder').innerHTML = '<img class="TipTip"
title="'+TitleDesc1+'" src="'+userpic+'" style="width:60px; height:66px" alt="user
picture">';
}
</script>
This works correctly. However, when I try to make the user picture clickable (onclick #2) (by adding a href) to show the user's site statistics the function does not open the Stats Box (a div that should be hidden until the onclick#2 (DisplayUserStats) WITHIN the javascript function):
<script language="javascript" type="text/javascript">
function ShowUser(userpic,username) {
var TitleDesc1 = 'Click this photo to learn more about '+username+ '';
document.getElementById('UserPicHolder').innerHTML = '<a href="#null"
onclick="DisplayUserStats("'+username+'")"><img class="TipTip" title="'+TitleDesc1+'"
src="'+userpic+'" style="width:60px; height:66px" alt="user picture"></a>';
}
</script>
The user's Stats Box div becomes visible, as expected, when the function DisplayUserStats() is empty (as DisplayUserStats() ), but of course the stats are undefined since no username has been defined. It's only when seemingly ANY content is placed inside DisplayUserStats() that the Stats Box div does not open (e.g. DisplayUserStats(dummystring) does not open the Stats Box div. Note that I have tried several other concatenations (thinking I did this incorrectly), for example, +username+ '+username+' username etc. Could someone please shed some light on how the variable username can be passed to the function DisplayUserStats()?
It would really look cleaner if didn't use inline event handlers. But the problem is that you have double quotes inside double quotes (thus broken HTML):
<a href="#null" onclick="DisplayUserStats("SomeUsername")">...
You can fix that with this ugly thing:
onclick="DisplayUserStats(\''+username+'\')">
Also, don't break lines when defining JavaScript strings, or the code will fail.

Categories