javascript image swap affects too many images - javascript

ive got a collection of 3 images, two small one large. id like to to be set up so when you click on a small image, it takes the place of the larger one. The issue is that I have a collection of three of these three images so when you click on a small image, it takes the spot of all three large images. Any suggestions for getting it so it only takes the spot of the large image in its section? Heres some code. Thanks!
$(document).ready(function(){
$('img').click(function(){
var url = $(this).attr('src');
$(this).parents('.picture-container').find('.large-picture > img').attr('src', url);
$('.large-picture > img').attr('src', url);
$(this).attr('src', bigUrl);
});
});
picture section (there are three of these)
<div class = 'picture-container'>
<div class = 'large-picture' style = 'width:50%;height:100%;float:left;'>
<img src = 'close_table_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'picture-content' style = 'float:right;width:45%;height:100%;'>
<div class='picture-title'>BOUTIQUE PRODUCTION STUDIO</div>
<div class='picture-text'>We built a boutique full service production studio that allows for one, two and three person filmed interviews and conversations. We have studio lights, a three camera set-up and remote monitoring. Additionally, our Infinity Wall creates a clean and professional look that allows the film to be about the message.</div>
<div class = 'small-picture-wrapper'>
<div class = 'small-picture' style = 'float:left;height:100%;'>
<img src = 'hair_and_makeup_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'small-picture' style = 'float:right;height:100%;'>
<img src = 'infinity_wall_dupontstudios.png' width = '100%' height = '100%'>
</div>
</div>
</div>
</div>

There are a bunch of jquery slideshow/carousel plugins that should do what you need.
If you need a snippet to just do this one thing, you might need to clarify what you want.
From what I gather, there should only be 3 images at any time. One is large, the other two are small ( like thumbnails? ). You want to click on a small image and have it replace the large image ( so the small image becomes as large as the large image and takes it's position?).
DOes the large image then shrink and take the place of the image just selected.
Just explain it like you would to a little kid.

I don't think I changed anything in the html other than the img src's, so this should work:
<script>
$(document).ready( function(){
$(".small-picture > img").click( function(){
var small_img = $(this);
var small_img_src = small_img.attr("src");
var img_container = small_img.closest(".picture-container");
var large_img = img_container.find(".large-picture > img");
var large_img_src = large_img.attr("src");
large_img.attr("src", small_img_src);
small_img.attr("src", large_img_src);
});
});
</script>

Related

When hovering over text, change the text and background image

I am new to coding and wrapping my head around utilization of JavaScript it still hard for me.
My problem is that I have like a navigation menu, those have one word in them. I want that when I hover over navigation menu background of the entire site changes corresponding to the navigation menu item I hovered over, and the navigation item changes it's content from one word to more words.
I tried searching on Google, YouTube and here on stackoverflow of course. I managed to get working code but it feels like a mess and bad practice and I wasn't able to implement good answers to my code or they were using ES5 JavaScript which differentiates from ES6 a lot.
Here are the things I tried:
1 . First thing i tried is to create a function with if statements. Didn't quite work. Probably because of my low understanding of JS.
I tried then to addEventListener to every navigation menu item individually. And that works, but it's a mess. Just blocks of copy / pasted code.
I tried then to create a function again and have onmouseover = "function()" inside of HTML but didn't work either.
Then I tried to do it over CSS but my inexperience started to show again it seems. I wasn't able to succeed in it with :before and :after either.
I have some example code here.
<div id='bckgimg'>
<div class="nav-container">
<a href='/nav1' id='nav-nav1' class='nav'>NAV1</a>
<a href='/nav2' id='nav-nav2' class='nav'>NAV2</a>
<a href='/nav3' id='nav-nav3' class='nav'>NAV3</a>
<a href='/nav4' id='nav-nav4' class='nav'>NAV4</a>
</div>
</div>
<style>
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
}
</style>
<script>
const nav1 = document.getElementById('nav-nav1');
const nav2 = document.getElementById('nav-nav2');
const nav3 = document.getElementById('nav-nav3');
const nav4 = document.getElementById('nav-nav4');
const bckgImg = document.getElementById("bckgimg");
// repeat this code 3 more times with nav2, nav3, nav4
// code bellow checks if <div> is hovered over and changes background image <div> + changes text of the <div>
navStories.addEventListener('mouseenter', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/2/300/200')";
navStories.innerHTML = "MY NAV 1 LONGER";
});
// if <div> is hovered out it returns the original picture to background <div> and original text of <div>
navStories.addEventListener('mouseleave', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
navStories.innerHTML = "NAV1";
});
</script>
Alright figured it out! Took me whole day but I got it!
First of, on JSfiddle where it says JavaScript + No-Library (pure JS) you need to press on the arrow on the side and for LOAD TYPE choose no wrap - bottom of body.
Second, if you have code which has an error which is represented by red color by JSfiddle your whole directory (JavaScript directory in my case) won't run. Error in my code was that I just commented all the code I didn't need at the bottom with /* but didn't close it since I thought it wasn't important.
Third, the solution itself:
// changed whole thing, which was my point. Reduced code from ~50 lines to two functions in 16 lines
// onHover function has a property of i which corresponds to numbers in html on onmouseover and out
// created arrays with IDs, what text and image should be after hovering
// i will correspond to numbers in html which in turn correspond to numbers in arrays
function onHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["MY NAV 1 LONGER", "MY NAV 2 LONGER", "MY NAV 3 LONGER", "MY NAV 4 LONGER"];
const bckgUrls = ["url('https://picsum.photos/id/2/300/200", "url('https://picsum.photos/id/3/300/200')", "url('https://picsum.photos/id/4/300/200')", "url('https://picsum.photos/id/5/300/200')"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = `${bckgUrls[i]}`;
}
// when hovering out from text do same like onHover just the reverse
// return values of navigation menu and background image to original
function outHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["NAV1", "NAV2", "NAV3", "NAV4"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
}
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
overflow: hidden;
background-position: center center;
background-size: cover;
height: 300px;
}
a {
color: white;
text-decoration: none;
}
<div id='bckgimg'>
<!-- because we changed ON LOAD options now onmouseover and on mouseout will pull functions from JS -->
<div class="nav-container">
<a onmouseover="onHover(0)" onmouseout="outHover(0)" href='/nav1' id='nav-nav1' class='nav'>NAV1</a><br>
<a onmouseover="onHover(1)" onmouseout="outHover(1)" href='/nav2' id='nav-nav2' class='nav'>NAV2</a><br>
<a onmouseover="onHover(2)" onmouseout="outHover(2)" href='/nav3' id='nav-nav3' class='nav'>NAV3</a><br>
<a onmouseover="onHover(3)" onmouseout="outHover(3)" href='/nav4' id='nav-nav4' class='nav'>NAV4</a><br>
</div>
</div>

Javascript Hover Text

I am trying to create a hover that shows a list to the user and reminds the user what we can accept.
<div class="proofresidencytip" style="display:inline-block;">
Hover Picture
</div>
$(".proofresidencytip").hover(
function(){
var message = "Please submit a copy of one of the following:";
var div = '<div class="rvtooltips">'+message+'</div>';
$(this).append(div);
$(this).find(".rvtooltips").fadeIn("fast");
},
function(){
var tt = $(this).find(".rvtooltips");
tt.fadeOut("fast", function(){
tt.remove();
});
}
);
http://jsfiddle.net/jw6zc4hf/
I am trying to figure out how I can list the items in var message. Whenever i try using <br> or any other html code it just breaks and doesnt show the message at all. How can I display new lines and the list of items in the hover?
Any help would be greatly appreciated!
I am not sure what the problem is? You can place <br> into message just fine:
$(".proofresidencytip").hover(
function(){
var message = "Please submit a copy of one of the following:<br>a<br>b";
var div = '<div class="rvtooltips">'+message+'</div>';
$(this).append(div);
$(this).find(".rvtooltips").fadeIn("fast");
},
function(){
var tt = $(this).find(".rvtooltips");
tt.fadeOut("fast", function(){
tt.remove();
});
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="proofresidencytip" style="display:inline-block;">
Hover Picture
</div>
If you have simplified your example in order to post the question on SO, you may have omitted some relevant CSS. If your proofresidencytip class has a set height, for example, it cannot easily expand. Make sure to set padding, line-height, perhaps min-height, but NOT height nor overflow: none.

How to do a simple image swap with JS?

I'm learning Javascript for my Intro to Programming Concepts class and I decided to make a simple photography portfolio site for my final project. I'm making the gallery now and I'm not sure how swap images.
This is what it looks like (cut off but you get the idea):
screenshot
This is the HTML:
<div id="gallery">
<div>
<img src="images/nature/1.jpg">
<br>
<div class="gallery">
<img src="images/nature/2.jpg">
<img src="images/nature/3.jpg">
<img src="images/nature/4.jpg">
<img src="images/nature/5.jpg">
<img src="images/wedding/1.jpg">
<img src="images/wedding/2.jpg">
<img src="images/wedding/3.jpg">
<img src="images/wedding/5.jpg">
<img src="images/wedding/4.jpg">
</div>
</div>
</div>
How do I make it so when you click an img from .gallery it swaps places with the first img (images/nature/1.jpg)?
The following should take whatever image is currently in the first image and swap it out with the one that is clicked:
var firstImage = document.getElementsByTagName('img')[0],
gallery = document.getElementsByClassName('gallery')[0];
gallery.addEventListener('click', function(e) {
var target = e.target;
if (target.tagName == "IMG") {
var newImage = target.src;
target.src = firstImage.src;
firstImage.src = newImage;
}
});
You can test it out here: https://jsfiddle.net/hxhe90qL/6/
After enough clicking around, however, the images will probably be all out of order. You could change it to only swap the first image by replacing the code inside the if statement to:
firstImage.src = target.src;
I think you mean when you click on swipe div, no matter what pic is showing in .gallery will be replaced by 1.jpg.
If that is the case, you can bind onclick event on .gallery, by getting event object, you can get access to the source dom element that triggers the event.
Then you can use javascript to change src attribute.
var gallery = document.querySelector('.gallery');
gallery.addEventListener('click', function(e) {
var targetImg = e.target;
targetImg.src = 'images/nature/1.jpg';
});

Image gallery thumbnails

I'm new to Java and need to build an image gallery.
I have a catalogue of images: each category has a thumbnail; each category has three images.
Process:
Click on thumbnail, bigPic changes its src to show the image you clicked on.
Three dots below bigPic can be clicked to see the other images in that category (so if another thumbnail is chosen, the srcs they pass onto bigPic will change too)
I have tried a few things and looked around but I cannot seem to make it work.
Here is what I have so far:
<script>
function backColor(a) {
document.getElementById("bigPic").src = a;
}
function varE(e){
var chosen = e;
document.getElementsByName("firstDot").id = chosen;
}
function setM(m) {
var chosenImage = m.id;
document.getElementById("bigPic").src = chosenImage;
}
</script>
bigPic:
<img class="bigPic" id="bigPic">
thumbnail image:
<img class="thumb" src="categoryImageSRC" onclick="backColor('anotherImageSRC'); varE('otherImageSRC')">
dot/circle that shows another image in category:
<img name="firstDot" id="" src="dotImageSRC" onclick="setM(this)">
Any ideas on how to go about this, examples and corrections are very welcome! Thank you!
get element by name returns an array of element so you need to change this line in varE function
document.getElementsByName("firstDot").id = chosen;
to
document.getElementsByName("firstDot")[0].id = chosen;

change target of javascript to div

I have some img tags with id's but through validating my code I realized that the tags were missing a src. The only problem is, is that in my javascript these img id's are targeted and when I changed them to a div instead the images disappeared.
Basically this page is staff profiles with images and content, the user clicks an arrow and it goes to the next profile. How the code works is that the images are in an external javascript file and when I click something on page and inspect the html I saw that the image appears within the image tags in HTML.This javascript was given to me so I am not sure what to change, I don't know much about javascript. Let me know if any clarification or code is needed, this is very difficult to explain as I don't understand what is going on.
HTML -the problem
<img id='staff_image' class='staff_image'></img>
<img id='staff_name' class='staff_name'></img>
HTML -the page
<div id='staff_slider' class='slider'>
<div class='staff_container'>
<img id='staff_image' class='staff_image' src"#" alt="image"
</div>
<img id='staff_name' class='staff_name' src"#" alt="image"></div>
<div id='staff_details' class='staff_details'></div>
</div>
<div class='slider_navigation'>
<img class='navLeft' src='../assets/images/staff_profile/slider/navLeft.png' alt= "nav left" onclick='navigate(-1);'/>
<img class='navRight' src='../assets/images/staff_profile/slider/navRight.png' alt="nav right" onclick='navigate(1);'/>
</div>
</div>
<script src="staff_profiles.js"></script>
<script src="slider.js"></script>
<script>
navigate(0);
</script>
JAVASCRIPT- slider.js (this is for two arrow buttons that scroll through the profiles)
var slider_index = 0;
function navigate(direction){
slider_index += direction;
if(slider_index < 0)
{
slider_index = profiles.length - 1;
}
else if(slider_index == profiles.length)
{
slider_index = 0;
}
loadProfile(profiles[slider_index]);
}
function loadProfile(profile)
{
var staff_image = document.getElementById('staff_image');
staff_image.src = imgPath + profile.img;
var staff_name = document.getElementById('staff_name');
staff_name.src = titlePath + profile.title;
var staff_details = document.getElementById('staff_details');
staff_details.innerHTML = profile.details;
}
JAVASCRIPT - staff_profiles.js (seperate file, these are the links to the images needed for the profiles, the content are in strings)
var imgPath = "../assets/images/staff_profile/staff/";
var titlePath = "../assets/images/staff_profile/titles/";
var profiles =
[
//
{
img:"fin.jpg",
title:"fin.png",
details:"<p>Stunt pilot with the Red Arrows (UK airforce stunt team), has served in combat choppers in 3 recent wars, and fears nothing except small dogs and single women.</p>" +
"<p>Owns an Extra EA-200 for the ultimate full stunt flight experience, and flies all our other fixed wing craft much more sedately when required. And, yes, that is his real name. He's Irish and he doesn't want to talk about it.</p>"
},
//
{
img:"hans.jpg",
title:"hans.png",
details:"<p>Hans has flown almost everything there is to fly. Hanshas has flown almost everything there is to fly. He first took the controls of a small plane at 12 years old, and flew solo when he was 14. After a few years flying anything anywhere he settled into a series of test pilot jobs but left that because he prefers company when hes in the air.</p>"
},
//
{
img:"john.jpg",
title:"john.png",
details:"<p>With over 10,000 hours piloting helicopters in the bush and mountains of the Southern Alps for deer recovery and mountain rescue operations, Doc is well qualified to land you and your friends in remote parts of the country that only he knows about. He ll help you plot your route, drop extra provisions where you want them, and pick you up when your done.</p>"
},
{
img:"wendy.jpg",
title:"wendy.png",
details:"<p>13 years commercial pilot in Africa, Russia and South America, during which she survived 3 crashes (none her own fault, she maintains). Owns a Cessna-172Skyhawk P that is ideal for low level sight seeing, rides a Harley and is a ski instructor during the seas</p>"
}
];
You need to change the following lines in the loadProfile function
var staff_image = document.getElementById('staff_image');
var myimg = staff_image.getElementsByTagName('img')[0];
myimg.src = imgPath + profile.img;
The HTML could be like this
<div id='staff_image'>
<img src"#" alt="image"/>
</div>
Hope it's useful to you

Categories

Resources