Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class.

.my_image_class:hover{
 border:3px solid blue;
-webkit-box-sizing: border-box; }

This makes the images bordered in blue when hovered over, giving a "selected effect". I want to maintain this effect even after selecting the image, similar to https://i.sstatic.net/bChVb.png.

Any suggestions on how can achieve this with JavaScript?

Answer №1

CSS-only Image Selector

Originally this question sought a CSS-only solution, and while achieving it without JavaScript is challenging, there is a clever CSS "hack" to partially address the issue:

img {
  margin: 3px;
  width: 100px;
}
img:hover, img:target {
  border: 3px solid green;
  margin: 0;
}
<a href="#a"><img id="a" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" /></a>
<a href="#b"><img id="b" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" /></a>

This method allows styling images as click targets within anchor tags using only CSS properties.

It's important to note that this technique only allows for selecting one image at a time.


JavaScript Image Selector

For those preferring a JavaScript approach, the following code can be utilized:

function select(element) {
  element.onclick = function() {
    element.classList.toggle('selected');
  }
}

Array.from(document.getElementsByClassName('selectable')).forEach(select);
img {
  margin: 3px;
}
.selected {
  border: 3px solid green;
  margin: 0;
}
<img class="selectable" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" />
<img class="selectable" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" />

This script adds the ability to select multiple images by toggling the "selected" class on click events.

To restrict users from selecting more than one item, simple adjustments in the provided JavaScript code can be made.

function select(element) {
  element.onclick = function() {
    var selected = document.getElementsByClassName('selected')[0];
    if (typeof selected !== 'undefined') { selected.classList.remove('selected'); }
    if (element !== selected) { element.classList.add('selected'); }
  }
}

Array.from(document.getElementsByClassName('selectable')).forEach(select);

Answer №2

To achieve hovering effects, utilizing jQuery can be beneficial. jQuery offers the hover() pseudo-event, which typically provides smoother functionality compared to mouseenter/mouseleave events. Consider creating separate CSS classes for each state (normal and hovered) and then dynamically changing the class on hover:

$(document).ready(function() {
    $(".my_image_clas").hover(
        function() { $(this).addClass("Hover"); },
        function() { $(this).removeClass("Hover"); }
    );
});

.my_image_clas.Hover { border: 3px solid blue; }

@Francesco Monti I acknowledge your input.

When working with jQuery, ensure to include the jquery.js file within the head tag of your HTML document:

<head>
<script src="jquery-1.12.0.min.js"></script>
</head>

Alternatively, you can reference the jQuery library online:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head> 

Within your script tags, use $(document).ready(function() to ensure proper execution.

If preferred, you can modularize your JavaScript and CSS files and include them accordingly.

Answer №3

Your estimated CSS:

.object {
    box-sizing: border-box;
    border: 2px solid transparent;
}

.object.active,
.item:hover,
.item:focus {
    border: 2px solid blue;
}

A few jQuery basics:

$('.item').on('click', function (event) {
    event.preventDefault(); // Stop the default action if .item is a link or button

    $(this).toggleClass('active');
})

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

TypeScript Implementation of ES6 Arrow Functions

Just diving into Typescript, I'm struggling to figure out the solution. I tried researching and looked into destructuring, but still unable to make it work. import React from "react"; import { StyleSheet, Text, View } from "react-native"; const st ...

Difficulty encountered when choosing and interacting with website button with the utilization of Python 3.5.1 and Selenium 2.53.2

I am currently utilizing a Macbook Air that runs on OS X El Capitan. My tool of choice is Python IDLE, and I am attempting to target and interact with the button located on the webpage below: <div class="search-form-actions"> <button class="btn ...

JavaScript Pagination and JSON Concerns in Coding Techniques

Currently, I am pre-caching a dataset with a maximum limit of 500. The Ajax request fetches all the data at once, allowing for front loading and pagination. Everything works fine this way. However, we are in the process of transitioning our backend archit ...

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...

Using CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

The content at “http://localhost:3000/script.js” could not be accessed because of a MIME type mismatch with the X-Content-Type-Options set to nosniff

I encountered an issue while attempting to transfer all the JavaScript to a separate js file and then adding that js file to the html per usual. The console displayed the following error message: The resource from “http://localhost:3000/public/main.js” ...

Troubleshooting async/await issues in certain IDEs

I've been experimenting with aysnc and await in my project. While it worked perfectly in FiddleJS, I encountered an error when trying to implement it in my IDE (PHPSTORM 2017): async function test(url){ ^^^^^^^^ SyntaxError: Unexpected token f ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

Error connecting to Firebase Cloud Functions - connection issue

Whenever I call my cloud function, I see the following message in the logs: Function execution took 5910 ms, finished with status: 'connection error'. It seems to be related to promises and returning or !d.exists, but I haven't been able to ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

I have been unable to find a solution for the non-functioning jQuery (3.4.1 / 3.3.1) load() issue

I have been working with jQuery's .load() function Take a look at my code snippet: <html> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://code.jquery.com/jquery-3.4.1.js"> ...

What steps can be taken to ensure the Instagram logo remains visible even when it is being hovered over?

Struggling to incorporate a social media icon on my website, I am facing an issue where the Instagram icon outline disappears on hover due to the gradient styling in CSS3. Below is my current code: .social-icons li.instagram a { border-radius: 50%; ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

FullCalendar dayClick event fails to trigger any action

I'm having trouble implementing the dayClick function in my fullCalendar. Despite setting up the calendar correctly, nothing happens when I click on a day. Here is the code I am using : var calendar; $(document).ready(function(){ app.init(); ...

After changing the page, the Facebook JS SDK fails to function properly when using JQueryMobile

I'm facing an issue with my webapp that utilizes jQuery Mobile for full ajax navigation. I have initialized the Facebook SDK at the pageinit event in jQueryMobile (called on each page). jQuery(document).on('pageinit', function (event) { ...

What is the most elegant way to retrieve a new item from Firebase and read it?

My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

Retrieve the screen width using a JavaScript function and apply it as a percentage

I find myself needing to adjust the size of table elements based on the width of the screen. While I am not well-versed in javascript or html, resolving this issue is crucial. Unfortunately, I did not create the original asp page and have limited ability t ...

Error throwing when attempting to use additional plugins in Angular CKEditor

I have been attempting to utilize the angular ckeditor extension found at: https://github.com/lemonde/angular-ckeditor UPDATE: I have already injected 'ckeditor' into the app modules. Within my partial html, I am including the following direc ...

Ways to create a back-and-forth transition across a sequence

Is it possible to create an animation that changes the width of an element once, then reverts back after a pause? I want this transition to occur over a three-second interval followed by a two-second delay. How can I achieve this? Below is the code I have ...

res.cookie function is unable to set cookies in the Chrome web browser

During development, I have a basic login page running locally on my machine (http://127.0.0.1:5500/index.html) and a simple express server running at http://localhost:3003 Despite seeing the server sending my access_token in response headers, Chrome brows ...