Which is better for creating hover effects: CSS3 or JavaScript?

When hovering over a link, I want to highlight a specific picture and blur the rest. Here's my HTML code:

    <body>
      <div id="back">
        <div id="one"></div>
        <div id="two"></div>
      </div>
      <div id="menu">
        <a href="one.html" id="link1">one</a>
        <a href="two.html" id="link2">two</a>
      </div>
     </body>

Here's the corresponding CSS code:

#Back{
position: absolue;
background-image: url(images/fond.png);
width: 960px;
height: 600px;
margin: 0 auto;
}
#one{
background-image: url(images/formation.png);
width: 960px;
height: 600px;
z-index:1;
}
#two{
background-image: url(images/experiences.png);
width: 960px;
height: 600px;
z-index:2;
margin-top:-600px;
 }

I've attempted the following in CSS:

#link1:hover #one{
  display:none;
}

And also tried a JavaScript solution like this:

function over(id){

if(document.getElementById(id)){

var objet = document.getElementById(id);

objet.style.display = "none";

}

}

Unfortunately, neither approach seems to be working as expected. Any guidance or solutions would be greatly appreciated!

Answer №1

HTML:

<div id="menu">
    <a href="one.html" id="link1">link1</a>
    <a href="two.html" id="link2">link2</a>
</div>
<div class="div0" id="zero">
    <div class="div1" id="one"></div>
    <div class="div2" id="two"></div>
</div>

CSS:

.div0 {
    position: absolute;
    top: 30px;
    left: 0px;
    background-image: url(http://www.sanbarcomputing.com/images/js.jpg);
    background-size: 400px 400px;
    width: 400px;
    height: 400px;
    transition: 1s;
}
.div1 {
    position: absolute;
    top: 30px;
    left: 0px;
    background-image: url(http://www.sanbarcomputing.com/images/html5-logo.png);
    background-size: 200px 200px;
    width: 200px;
    height: 200px;
    transition: 1s;
}
.div2 {
    position: absolute;
    top: 30px;
    left: 200px;
    background-image: url(http://www.sanbarcomputing.com/images/class-header-css3.jpg);
    background-size: 200px 200px;
    width: 200px;
    height: 200px;
    transition: 1s;
}

JavaScript:

(function () {
    var zeroEl = document.getElementById('zero'),
        oneEl = document.getElementById('one'),
        twoEl = document.getElementById('two'),
        link1El = document.getElementById('link1'),
        link2El = document.getElementById('link2');

    function mouseover (elem) {
        elem.style.opacity = '.2';
        zeroEl.style.opacity = '.2';

    }

    function mouseout (elem) {
        elem.style.opacity = '1';
        zeroEl.style.opacity = '1';
    }

    document.addEventListener('DOMContentLoaded', function () {
        link1El.addEventListener('mouseover', function () {
            mouseover(oneEl); }, false);
        link2El.addEventListener('mouseover', function () {
            mouseover(twoEl); }, false);
        link1El.addEventListener('mouseout', function() {
            mouseout(oneEl); }, false);
        link2El.addEventListener('mouseout', function () {
            mouseout(twoEl); }, false);
    }, false);
})();

jsfiddle

I struggled to implement the CSS hover solution, unfortunately.

NOTICE: This approach utilizes contemporary JavaScript methods that may not be supported by older browsers

ADJUSTMENT: Revised using Pavlo's opacity technique, corrected css mistakes, modified image alignments, converted images into separate divs

Answer №2

To start off, make sure to assign a unique class to each link:

<div id="menu">
   <a href="one.html" class=".link" id="link1">one</a></div>
   <a href="two.html" class=".link" id="link2">two</a></div>
</div>

If your css hover effect isn't working as expected, you can try using jQuery instead:

$('.link').hover(function() {
  //handle mouse enter

}, function() {
  //handle mouse leave
});

For more information, check out: http://api.jquery.com/hover/

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

How can Angular be used for live search to provide precise search results even when the server does not return data in the expected sequence?

Currently, I am in the process of constructing a website for one of my clients. The search page on the site is designed to update search results as you type in the search bar - with each keystroke triggering a new search request. However, there's an i ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Finding the dynamic width of a div using JavaScript

I have two divs named demo1 and demo2. I want the width of demo2 to automatically adjust when I drag demo1 left to right or right to left. <div class="wrapper"> <div class="demo"></div> <div class="demo2"&g ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

Tips on saving this information in a MySQL database

I'm currently developing a php script that collects and saves links in mysql. However, I've encountered an issue where the script sometimes captures multiple links for the same download, as shown below: http://www.fileserve.com/file/XXXXXX http: ...

What is the best way to include scrollbars with bootstrap?

I recently came across this HTML code snippet from a learning website: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Example of Bootstrap 3 Simple Tables</title> <link rel="stylesheet" href="htt ...

Link an HTML contact form to an Express.js backend server

Hey there, I'm a newcomer to web development and I've been working on creating the backend code for a contact form, but it keeps throwing errors. Here's my HTML code for the contact form: </div> <div class="row"> ...

return to the original secured page based on the most recent language preference

I'm facing an issue with a logical redirection that needs to redirect users to the previous protected page after login. The login functionality is implemented using my custom login page and Google Credentials. Additionally, I have set up a multilingu ...

Leveraging jQuery.ajax() for retrieving c# WebMethod data triggers the error message of 'Unidentified Web Method'

I am diving into the world of jQuery.ajax() for the first time to call a WebMethod. Despite my efforts searching on stackoverflow and Google countless times, I seem to be stuck in a cycle of trial and error with random solutions. It's reached a point ...

Transferring data from one of the three submitted forms by utilizing jQuery's AJAX function

Currently, I am facing a challenge with three forms on a website, where two of them are located in modal windows. My goal is to use ajax to send input values such as name, phone, email, and radio button selections (which vary in each form). However, I have ...

Checking variable length time with JavaScript Regular Expression

My specific requirement is to validate a string ranging from 1 to 4 characters in length (where H stands for hour and M represents minutes): If the string has 1 character, it should be in the format of H (a digit between 0-9). A 2-character string should ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

"Can anyone provide guidance on how to use Twig to read from a JSON file

I currently have a basic PHP file set up as follows: <?php // Loading our autoloader require_once __DIR__.'/vendor/autoload.php'; // Setting the location of our Twig templates $loader = new Twig_Loader_Filesystem(__DIR__.'/views& ...

Ways to ensure next/image takes up all available grid space

Is there a way to make the next/image element span from grid 1 through 8? It seems to work fine with the imgtag but not with next/image. .project { display: grid; margin-bottom: 4rem; grid-template-columns: repeat(12, 1fr); align-items: center; } ...

Learn how to create a logarithmic scale graph using CanvasJS by fetching data from an AJAX call

window.onload = function() { var dataPoints = []; // fetching the json data from api via AJAX call. var X = []; var Y = []; var data = []; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("applicatio ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Top technique for verifying the presence of duplicates within an array of objects

How can I efficiently check for duplicates in typescript within a large array of objects and return true or false based on the results? let testArray: { id: number, name: string }[] = [ { "id": 0, "name": "name1" }, ...

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...