Utilize Various Guidelines for Clicking on Various Thumbnails (jquery)

I am new to the world of HTML/CSS and have been struggling with a jQuery challenge while building my first website. My goal is to create a jQuery-powered image gallery using thumbnails. I found a tutorial by Ivan Lazarevic () and also sought help from Stackoverflow's forum via this thread: .

The code provided replaces the displayed large image with a larger version of the thumbnail when clicked. However, this works smoothly only for pictures with the same orientation. To address this, I have separate code snippets in two different files for horizontal and vertical images:

   <div id="mainImage">
     <img id="largeImage" src="Images/Projects/UOW/UOWII_large.jpg"/>
   </div>

AND:

   <div id="mainImageVERTICAL">
     <img id="largeImageVERTICAL" src="Images/Projects/UOW/UOWI_large.jpg" />
   </div>

I have created different CSS rules for largeImage and largeImageVERTICAL based on portrait or landscape orientation of the images.

   #largeImage { 
   position: fixed;
   height: 83%;
   width:auto;
   top: 15%;
   left: 5%;
   }

AND:

   #largeImageVERTICAL { 
   position: fixed;
   height: 83%;
   width:auto;
   top: 15%;
   left: 36.36%;
   }

These rules position the images differently on the screen. However, I am seeking guidance on how to modify my code so that I can handle both portrait and landscape-oriented images by applying the correct CSS rule to each. Currently, I am following Lazarevic's approach which includes:

   $('#thumbs img').click(function(){
   $('#largeImage').attr('src',$(this).attr('src').replace('thumb','large'));
   });

This code simply swaps the thumbnails with larger images. I want to dynamically apply the appropriate CSS rule based on the orientation of the image clicked. I believe this requires some JavaScript coding, which I am not familiar with.

I would greatly appreciate any assistance to move forward with this project. Any suggestions on how to achieve this? Perhaps a JS function that determines which CSS rule to use based on the clicked image? I am currently stuck and in need of guidance...

Thank you in advance!

Answer №1

There are a few different ways you can accomplish this task.

One method is to utilize the HTML5 data- attribute to indicate which specific <img> elements should be modified. For example:

<div id="thumbs">
    <img src="img.jpg" data-large="largeImage"/>
    <img src="anotherimg.jpg" data-large="largeImageVERTICAL"/>
</div>

Then, you can implement the following code:

$('#thumbs img').click(function(e) {
    var imageId = $(this).attr('data-large'),
        newSrc = this.src.replace('thumb', 'large');
    $('#' + imageId).attr('src', newSrc);
});

Alternatively, you can determine whether an image is portrait or landscape based on its thumbnail dimensions:

$('#thumbs img').click(function(e) {
    var $this = $(this),
        height = $this.height(),
        width = $this.width(),
        newSrc = this.src.replace('thumb', 'large');
    var imageId = (height > width) ? 'largeImageVERTICAL' : 'largeImage';
    $('#' + imageId).attr('src', newSrc);
});

In either scenario, it's important to hide the other unused <img> element to prevent displaying the previously selected image for the alternate orientation.

One approach to accomplishing this could involve:

var alternateImageId = (imageId === 'largeImage') ? 'largeImageVERTICAL' : 'largeImage';
$('#' + alternateImageId).hide();

You can include the above lines within the click event handler and use .show() after updating the source with .attr('src', ...).

Answer №2

Utilize classes instead of ids for styling.

.large-image{ 
   top: 15%;
   width:auto;
   height: 83%;
   position: fixed;
}
.portrait{ 
   left: 36.36%;
}
.landscape{ 
   left: 5%;
}

JavaScript

$('.large-image').on('load', function () {
    var that = $(this);
    if (that.width() < that.height()) {
        that.addClass('portrait');
    } else {
        that.addClass('landscape');
    }
});
$('#thumbs').on('click', 'img', function () {
    $('.large-image').attr('src',$(this).attr('src').replace('thumb','large'));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that video controls remain visible for 3 seconds after hovering over them

Is there a way to make video controls only appear when hovering over the video and then disappear after three seconds when the cursor is moved away? The current behavior works correctly when the video is at the beginning, but if I hover while it's pla ...

What is the best method for sending a DbGeography parameter to MVC?

I am working on developing an API that allows users to save polygons on the server using ASP.NET MVC 5. Can anyone guide me on how to properly format the AJAX parameters for posting requests with DbGeography? This is what I have tried so far: $.ajax({ ...

I'm having trouble getting the drag event to work for Three.js trackball controls within a UIkit

The issue at hand involves a fullscreen Three.js canvas that is functioning perfectly, but there are limitations when displaying a preview in a UIkit modal – zooming works, but panning does not. JS: Renderer and Controls renderer = new THREE.WebGLRende ...

What is the most effective method for enlarging an image based on its position within a larger image?

I currently have a div element that displays an image as a sprite cut from a larger image. Here is the CSS code for it: .myDiv { background-image: url("myBiggerImage.jpg"); background-position: -51px -798px; background-repeat: no-repeat; b ...

What are the steps to update content by referencing an id in the hash URL?

Currently, I am utilizing the following code snippet to extract an ID from the hash URL: var integer = window.location.hash.match(/\d+/) | 0; alert(integer); However, I have encountered an issue where upon using the back button after modifying the U ...

What exactly is the purpose of the double ampersand selector, '&&', when it comes to overriding the root class with makeStyles within Material-UI React?

I recently started using Material-UI and encountered an issue where I couldn't override the root class for Avatar, specifically MuiAvatar-root. Material-Ui Version: 4.11.3 Despite following examples provided by material-ui's documentation here, ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...

Eliminate borders surrounding WordPress text widgets

Looking for some help with removing the border around the widgets on my home page. Despite my theme's CSS removing borders universally, I thought targeting specific Div text widgets (such as text-7, text-6) would do the trick. While I can control the ...

Retrieve webpage content using an ajax request in JavaScript

I'm working on an HTML page with an Ajax call to load table content. <html> .... <script sec:haspermission="VIEW_NOTE" th:inline='javascript'> require(['app/agent/viewGlobalAgent'], function (){ ...

Increase the size of a div to equal the combined width of two divs located directly below it

I need help aligning 3 divs so that the top div stretches to match the width of the bottom 2 divs combined. Here is an image showing the expected div positioning. I attempted to use display: table-row for the divs. <div id="main_div" style="display: ta ...

Text Appearing in Bold Typeface

It's strange that the text below the "Support Us" section is showing up in bold. I tried changing the font style to normal, but it's still bold. The JSFiddle layout may appear messy, but if you scroll right, you'll see the issue. http://jsf ...

Create an event that binds to the immediate parent element and triggers upon the element's close

Throughout my coding journey, I've often found myself writing jQuery code like the example below to attach event functions to nearby elements. However, yesterday a friend pointed out that it may be more efficient to attach the event function to their ...

In need of a solution for the blank space issue in my HTML/CSS slideshow. How can I

I am experiencing an issue with my slideshow where there is a blank area on the right side. I have tried several solutions but haven't had much success resolving it. Any suggestions would be greatly appreciated. Thank you! Link to image JSFiddle lin ...

Tips for integrating Bootstrap JavaScript into a React project

I am encountering an issue while trying to incorporate Bootstrap JavaScript into my web app. I have successfully included the CSS, but I am facing difficulties with Bootstrap JavaScript for components like modals and alerts. My package.json includes: "boo ...

Mouse click failing to trigger CSS property update

I am attempting to create an accordion feature. I want the accordion to expand when hovering over the "accordion head," and also show/hide the accordion body when clicking on the "accordion head." I have successfully implemented the show/hide functionalit ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

Utilize paperclip and angularjs to easily upload files

I am currently working on integrating Angularjs upload functionality into my rails application: Angular File upload Below is my controller code for managing photos: def create @photo = current_user.photos.new(photo_params) respond_to do |format| if @ ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

When the page is refreshed, the route fails to load the data

My Vue.JS website is quite simple, utilizing VueX and Vue-Router. I have defined two routes: '#/' and '#/account/' These routes are filled with components from .vue files, loaded dynamically upon page load using http-vue-loader (to avo ...

Enhance the appearance of the standard black rectangle displaying the messages "No video source" or "No video permissions"

Is there a way to change the styling of the video element that appears as a black rectangle with a strikethrough play button when the user is prompted for permission on Safari? Does it have a specific ID, class, or tag that can be targeted? I'm curre ...