What are some ways I can condense this code?

I have been working on improving my coding skills by learning jQuery. One of the tasks I tackled was creating a simple image showcase. However, the code I ended up with seems lengthy and not very efficient. Can anyone provide suggestions on how to enhance this?

HTML:

<div id="gallery">
  <div style="float: left; border: 1px solid red; width: 600px; height: 450px;background-image: url(images/main_image.png);" class="big_image"></div>
  <div style="float:left;" id="thumbnails">

  <div style="border: 1px solid red; cursor: pointer; width: 150px; height: 75px; background-image: url(images/thumbnail_1.png);" class="thumbnail_1"></div>
  <div style="border: 1px solid red; cursor: pointer; width: 150px; height: 75px; background-image: url(images/thumbnail_2.png);" class="thumbnail_2"></div>
  <div style="border: 1px solid red; cursor: pointer; width: 150px; height: 75px; background-image: url(images/thumbnail_3.png);" class="thumbnail_3"></div>
  <div style="border: 1px solid red; cursor: pointer; width: 150px; height: 75px; background-image: url(images/main_thumbnail.png);" class="main_thumbnail"></div>
  </div>
</div>

JS

<script type="text/javascript">
  $(function(){
    $(".thumbnail_1").click(function(){
      $(".big_image").css("background-image","url('images/image_1.png')");
    });
  });
  $(function(){
    $(".thumbnail_2").click(function(){
      $(".big_image").css("background-image","url('images/image_2.png')");
    });
  });
  $(function(){
    $(".thumbnail_3").click(function(){
      $(".big_image").css("background-image","url('images/image_3.png')");
    });
  });
  $(function(){
    $(".main_thumbnail").click(function(){
      $(".big_image").css("background-image","url('images/main_image.png')");
    });
  });
</script>

Answer №1

To avoid duplicate styling in your HTML, it is recommended to separate your styling into a linked CSS file:

HTML:

<div id="gallery">
   <div id="big_image"></div>
   <div id="thumbnails">

      <div id="t1" class="thumbnail"></div>
      <div id="t2" class="thumbnail"></div>
      <div id="t3" class="thumbnail"></div>
      <div id="tmain" class="thumbnail"></div>

   </div>
</div>

A general rule to follow is if you have inline styles with "style=" in your HTML, you may have too much inline styling.

CSS:

#big_image
{
float: left;
border: 1px solid red;
width: 600px; height:
450px;background-image: url(images/main_big.png);
}

#t1 {background-image: url(images/thumbnail_1.png);}
#t2 {background-image: url(images/thumbnail_2.png);}
#t3 {background-image: url(images/thumbnail_3.png);}
#tmain {background-image: url(images/main_thumbnail.png);}
#thumbnails {float:left;}

.thumbnail //<--- observe how all styling for class="thumbnail" is consolidated in one place!
{
border: 1px solid red;
cursor: pointer;
width: 150px;
height: 75px;
}

Optimize JavaScript by utilizing variables:

imageClick("#t1", "main_1")
imageClick("#t2", "main_2")
imageClick("#t3", "main_3")
imageClick("#tmain", "main_main")

 function imageClick(id, imageName)
{
       $(function(){
            $("").click(function(){
                $(id).css("background-image","url('images/' + imageName + '.png')");
            });
        });
}

Note that the imageClick() function is designed to be versatile for repeated use elsewhere. By passing ids as parameters and keeping them out of the functions, one code block can be reused multiple times.

Answer №2

What do you think of this idea?

$(document).ready(function() {
    $('#gallery div').click(function() {
        $('.main_image').css('background-image', 'url('+ $(this).data('img-url') +')');
    });
});

To make it work, make sure your clickable divs have a data attribute called img-url with the URL of the image you want to show when clicked.

<div data-img-url="images/beach.jpg"></div>

Answer №3

To enhance your div elements with a data attribute for the main image, assign a shared class to all of them.

<div data-main-image="images/gora_main_1.png" class="gallery-item" style...></div>

Next, leverage the data attribute using jQuery:

$(function(){
        $(".gallery-item").on('click', function(){
            var mainImage = $(this).data('main-image');
            $(".main_image").css("background-image","url('" + mainImage + "')");
        });
    });

Answer №4

Here are some tips to condense your code:

$('[class^="trumb_"]').each(function() {
    $(this).click(function() {
        var i = $(this).index() + 1;
        var imgUrl = "images/gora_big_" + i + ".png";
        $(".big_image").css("background-image","url('" + imgUrl + "')");
    })
});

$(".main_trumb").click(function(){
    $(".big_image").css("background-image","url('images/gora_big_main.png')");
});

Check out the DEMO here: http://jsfiddle.net/255Qv/

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

Using Python to manipulate HTML for printing purposes

As I develop an application in Python, one of the features requires printing PDF files using a Xerox printer. I am currently considering two options: First option: figuring out a way to communicate with the printer driver and send commands to the printer ...

Child element casting shadow over parent element

I am currently using box shadow for both the parent (.map) and child (.toggle-button): .map { position: fixed; top: 20px; right: 0; width: 280px; height: 280px; z-index: 9999; box-shadow: 0px 1px 6px 0px rgba(0,0,0,0.3); } .map ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

jQuery neglecting events of child elements

I am facing an issue with the following list structure: <ul id="menu"> <li style="background-image:url('Images/X-AFH-Company-Office-Background.png')" id="office"> <div >Company / Office</div> ...

Using setTimeout to click and hold on an element in Javascript

I am in need of adding a feature to my web app where a specific action is triggered when the user clicks and holds on an element, similar to the long press on Android. Here is the HTML code for my div: <div id="myDiv" onmousedown="press()" onmouse ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Tips for minimizing database queries for each data type

I'm currently developing an App that requires the user to input numbers into two different fields. The first field is for entering numbers, while the second field displays a calculation based on the input. Each time the user enters a number, a call to ...

Encountered an `EPIPE` error during the testing of a POST request with Jest

I have a simple server that is set up to handle POST requests and return a "413 Request entity too large" error if the request body exceeds the allowed size. During my testing with Jest, I've noticed that sometimes the correct error is returned, but m ...

Tips on preventing &ersand symbols from being processed through ajax requests, while preserving them as plain text

One challenge I am facing is with my comment form submission through ajax. Below is the ajax code snippet: $('#button').click(function(){ comment = $('#comment').val(); $.ajax({ type : 'POST', url ...

Accessing elements of a multi-dimensional Javascript array: A step-by-step guide

In my Java script array, the structure goes up to 5 levels deep with elements containing strings and arrays. photoList = [Photographs, [ [2000, [ [London, [pic1.jpg, pic2.jpg, pic3.jpg]], ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

Adding additional `select` dynamically causes the value to disappear from view

After attempting to replicate the functionality of the select field, I encountered an issue where it no longer displays any values. Specifically, if I opt for a small size, I encounter this error message in the console. https://i.stack.imgur.com/5hKX6.png ...

Editing a video directly within the browser prior to uploading it

For my new video upload platform, I am looking to give users the ability to trim their videos directly in their browser before uploading to the cloud storage. Can anyone suggest a Javascript solution for this feature? ...

Change the source of another element when clicked

Check out the fixed version of previously broken code here I am facing challenges in changing an attribute on another element from a click function sniping $('#black').click(function() { $('#blackbox').slideToggle('slow&apos ...

Looking to utilize the jQuery Colorbox plugin for submitting a form using AJAX

Is it possible to use the colorbox plugin to submit a form through ajax and display the response in a new modal window? For instance, a user clicks a link which opens a modal dialog. Upon submitting the form within this modal, the modal should update wit ...

How can you enable fullscreen for a featherlight iFrame?

I have implemented Featherlight to display an iframe within a popup modal on my website. If you click the iframe button, you can see a demo of how it works. One issue I am facing is that the generated iframe tag by Featherlight does not include allowfulls ...

What is the best way to dynamically insert an image into an <li> element?

I am looking to enhance my menu by adding an image below each li item as a separator. How can I achieve this using CSS? I want the images to automatically appear whenever a new li tag is added to the ul. Here is the HTML code: <ul class="menu"> ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Issues with dropdown checklist functionality

I'm having trouble creating a dropdown checkbox list for my blog. Every time I try to check one of the boxes, the list closes unexpectedly. Any assistance would be greatly appreciated! The element is essentially a styled dropdown with checkboxes embed ...

unable to alter color using CSS

So I've heard that the CSS code is good. Here is the HTML code I am using: <DOCTYPE! html> <html lang="nl"> <head> <title>The White Stripes!</title> <link rel="stylesheet" type="text/css" href="home.css"& ...