Switch the background image of a div when hovering over a different div that is not its parent or sibling

I am in the process of building a dynamic portfolio on WordPress and I need some help with a specific functionality. At the top of my page, I have a large banner image, followed by individual thumbnails of my work below. What I want to achieve is the ability to hover over these thumbnails and have them fade the header image into a larger version of the thumbnail, using the same image source.

The challenge arises from the fact that the page thumbnails are generated through cycling "portfolio" posts with featured images, meaning there are no direct relationships between the elements. This requires me to generate links dynamically using PHP code for the thumbs.

Initially, I explored the possibility of achieving this effect using CSS alone but realized it's not feasible due to the lack of parent or sibling connections between the elements. Do you think such a feature is possible? Would I need to implement JavaScript, despite my limited knowledge of the language compared to CSS/HTML?

You can view the website under construction here.

EDIT:

Below is the code snippet used to generate the thumbnails:

<?php
    $query = new WP_Query(array('posts_per_page' => 6, 'meta_key' => '_thumbnail_id'));
        while($query->have_posts()) : 
            $query->the_post(); ?>
            <div class="portfolioThumbnail"><a href="<?php the_permalink() ?>"><?php the_post_thumbnail(); ?></a></div><?php
            endwhile;
?>

In essence, the structure of the site is as follows:

<div id="backgroundThatNeedsToChangeOnHover"></div>

<navigation></nav>

<div id="content">

    <div class="portfolioThumbnail">
        <a href="spawnedByPHP"><img src="spawnedByPHP" /></a>
    </div>

    <div class="portfolioThumbnail">
        <a href="spawnedByPHP"><img src="spawnedByPHP" /></a>
    </div>

    <div class="portfolioThumbnail">
        <a href="spawnedByPHP"><img src="spawnedByPHP" /></a>
    </div>

</div>

Answer №1

Check out this basic jquery example: JSfiddle

$(function(){
  $('.thumb').click(function(){
    $('.header').css("backgroundImage", "url(" + $(this).attr("src") + ")");
  });
});

Enhanced version with hover and fade effects: JSfiddle

var url;
$(function(){
  $('.header').css("backgroundImage", "url( http://lorempixel.com/100/100/abstract/9 )");
  $('.thumb').hover(function(){
    url = "url(" + $(this).attr("src") + ")";
    $('.header').animate({opacity: 0}, 500, function(){
      $(this).css("backgroundImage", url).delay(100).animate({opacity: 1}, 500);
    });
  });
});

Answer №2

Encountered a minor issue with the header not reverting back to the original image, prompting the creation of this code solution. Is this efficiently coded? I'm considering adding animations to enhance both events.

$(function(){
    var headImg = $('.header').css("backgroundImage");

  $('.thumb').mouseover(function(){
    $('.header').css("backgroundImage", "url(" + $(this).attr("src") + ")");
  });

  $('.thumb').mouseleave(function(){
      $('.header').css("backgroundImage", headImg);
  });
});

JSFiddle Link

Updated JSFiddle now includes fade in/out and animation halting capabilities: Enhanced JSFiddle

$(function(){
    var headImg = $('.header').css("backgroundImage");
    var url;

  $('.thumb').mouseover(function(){
      url = "url(" + $(this).attr("src") + ")";
      $('.header').stop().animate({opacity:0}, 250, function(){
      $(this).css("backgroundImage", url).animate({opacity: 1}, 250);
      });
  });

  $('.thumb').mouseleave(function(){
      $('.header').stop().animate({opacity:0}, 250, function(){
          $(this).css("backgroundImage", headImg).animate({opacity: 1}, 250);
      });
  });
});

UPDATE: The delay() function has been removed from the code to ensure compatibility with Wordpress.

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

Utilize an Express.js controller to retrieve information from an API service and display it on the view

I need assistance with connecting an ExpressJS web app to an API system that responds only with JSON objects. The API system example is: http://example.com/user/13 response: {name:'Aesome 1', age: '13'} The ExpressJS web app cre ...

Navigate to a specific hidden div that is initially invisible

Currently, I am working on a web chat application using next.js. The app includes an emoji picker button, which, when clicked, displays a menu of emojis. However, the issue I am facing is that the user has to scroll down in order to see the emoji menu. I a ...

What strategies do you use to maintain semantic HTML and effectively manage extensive CSS for intricate designs seen on large portals or news websites?

Creating personal and small business websites is relatively easy, but when it comes to developing new sites, portals, and e-commerce platforms with a large amount of content on each page, it can be more challenging. What strategies do you use to maintain ...

The navigation bar buttons in my IONIC 2 app are unresponsive on both the

In Ionic 2 for Android, I encountered an issue with the title placement. To resolve this, I applied some CSS to center the title and added left and right buttons to the nav bar. However, when I tried to implement onclick functionality for these buttons, no ...

Having trouble with the JSFiddle dropdown button that is unresponsive to

I am currently in the process of developing a test drop-down menu. The open menu button functions correctly, however, the close button is unresponsive to clicking or hovering actions. Upon clicking the open menu button, it should make the other button visi ...

Safari users encountering invalid dates generated by Moment Js library

Can anyone explain why I am seeing "invalid date" in Safari, but it works fine in other browsers? moment('01/01/2023 11:44:00.000 AM').tz(time_zone, true).format('hh:mm:ss:SS A z') chrome https://i.sstatic.net/PeFBp.png safari https ...

HighCharts.js - Customizing Label Colors Dynamically

Can the label color change along with gauge color changes? You can view my js fiddle here to see the current setup and the desired requirement: http://jsfiddle.net/e76o9otk/735/ dataLabels: { format: '<div style="margin-top: -15.5px; ...

A thrilling twist on the classic game of Tic Tac Toe, where X and

I am having trouble with switching between the cross and circle symbols in my Tic Tac Toe game. The code seems to be set up correctly, but it's not functioning as expected. Any suggestions on how to fix this? Here is the JavaScript code: varcode va ...

Fill up mongoose with data on 3 schemas

I have successfully populated 2 schema, but I am facing difficulty in populating the third schema. Here are the schemas: Member Schema var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); var Schema = mongoose.Schema ...

What are the steps to integrating an HTML source with jQuery Autocomplete?

Struggling with a challenging ajax call to an HTML source that is essential. The goal is to convert the html response into a format suitable for displaying in the jQuery autocomplete list. Working with Autocomplete and Ajax $("#From, #To, #FromVacation ...

Constructing a hierarchical tree structure using an array of objects that are initially flat

My goal is to create a hierarchical tree structure from a flat array: The original flat array looks like this: nodes = [ {id: 1, pid: 0, name: "kpittu"}, {id: 2, pid: 0, name: "news"}, {id: 3, pid: 0, name: "menu"}, {id: 4, pid: 3, name: ...

Creating a Bootstrap grid system for multiple divs with offset styling

Looking to design an HTML page layout with a sidebar menu and a fixed KPI metrics div in the first row. Want the KPI metrics div to stay fixed when scrolling through tables below. Also, seeking guidance on aligning the KPI metrics div and the table div t ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...

Trouble with 'this.function' and handling scope within my code

Hi there! I'm having an issue with this code snippet: Whenever I reach line 109, I encounter an error message that reads "TypeError: Result of expression 'this.allVarsDefined' [undefined] is not a function." I find scope in javascript to b ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

What is the best way to deploy a Vue Webpack application using Sails.js?

I am currently managing a Sails.js server alongside a Vue Webpack application, running as separate entities. Here's how my folder structure is laid out: /application-root/server/ /application-root/client/ Within the /server/ directory lies my Sails ...

Guide to adding a new font to your Ember project

I am currently in the process of developing a website utilizing the MEEN Stack framework (Mongo, Ember, Express, Node). One challenge I am encountering is importing the Lato font family into my project to serve as the main font for the entire site. Despite ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

Is there a way I can implement lazy loading of results without having to overhaul my entire Laravel + jQuery application built in the Single Page Application style?

I recently created a web application using the Single Page Application concept, but without utilizing any modern technologies or frameworks. In this application, I have a jQuery page that makes dynamic requests to a localhost - a Laravel instance that comp ...