Is there a way to use jQuery to make a div fade in and toggle over another

I have created a test page and I am looking to achieve a specific effect when the page loads. I want everything on the page to be hidden initially. When I click on the "About" text, I want it to fade in using fadeToggle(); however, when I click on "My work," I want another text to fade in but overlap the previous one instead of appearing below it. Can anyone help me achieve this?

Here is my code snippet:

<script>
$(document).ready(function(){
    $(".thumbnail").hide();
    $(".work").click(function(){
        $(".thumbnail").fadeToggle('slow');      
    });
});


$(document).ready(function(){
    $(".person").hide();
    $(".about").click(function(){
        $(".person").fadeToggle('slow');      
    });
});
</script>

Answer №1

Give this a try.

$(document).ready(function(){
    $(".thumbnail").hide();
    $(".person").hide();

    $(".work").click(function(){
        $(".person").hide();
        $(".thumbnail").fadeToggle('slow');      
    });


    $(".about").click(function(){
        $(".thumbnail").hide();
        $(".person").fadeToggle('slow');      
    });
});

Modified according to feedback from Matthew Check out the demo here

Answer №2

Dealing with a common issue:

Facing the challenge of displaying multiple items, but only one at a time

An easy fix:

  • Conceal all elements
  • Show what you want to be visible

By following this approach, you encompass all potential solutions, including the scenario where no content is displayed, effectively bypassing certain phases.

In your particular situation:

function hideAll(){
 $(".thumbnail").hide();
$(".person").hide();
// ...... others ......
}

$(document).ready(function(){
    $(".work").click(function(){
        hideAll();
        $(".thumbnail").fadeToggle('slow');      
    });
    $(".about").click(function(){
        hideAll();
        $(".person").fadeToggle('slow');      
    });

hideAll();
});

Answer №3

If you're looking for an easy way to make your website more interactive, consider using the same click event names with the divs you want to open. This will allow for a modular approach that can work with as many sections as you'd like without constantly adding new functions.

With some slight adjustments to your HTML and a significant change in the JavaScript code, you can now easily toggle between different sections on your site. By incorporating fade effects for a smoother transition, the user experience is enhanced.

$(document).ready(function() {
  $('section').hide();
  $(".btn").click(function() {
    $('section').fadeOut('1000');
    $('section#'+$(this).attr('id')).delay('1000').fadeIn();
  });
});
/* CSS Document 
html {
    background: url(green.jpg) no-repeat center center fixed;
    background-size: cover;
} 
 */

body {
  font-family: 'Candara', 'Open Sans', 'sans-serif';
}
/* css for the shiny buttons */

.btn {
  cursor: pointer;
  margin: 10px;
  text-decoration: none;
  padding: 10px;
  font-size: 14px;
  transition: .3s;
  -webkit-transition: .3s;
  -moz-transition: .3s;
  -o-transition: .3s;
  display: inline-block;
}
.btn:hover {
  cursor: url(http://cur.cursors-4u.net/symbols/sym-1/sym46.cur), auto;
}
.contact {
  color: #000;
}
.contact:hover {
  background-color: #ecf0f1;
  color: #000;
  opacity: 0.5;
  filter: Alpha(opacity=50);
}
.about {
  color: #000;
}
.about:hover {
  background-color: #ecf0f1;
  color: #000;
  opacity: 0.5;
  filter: Alpha(opacity=50);
}
.work {
  color: #000;
}
.work:hover {
  background-color: #ecf0f1;
  color: #000;
  opacity: 0.5;
  filter: Alpha(opacity=50);
}
}
.buttons {
  padding-top: 30px;
  text-align: center;
  position: absolute;
  top: 50px;
  left: 100px;
}
.title,
.subtitle {
  font-family: 'Wire one';
  font-weight: normal;
  font-size: 5em;
  margin-bottom: 15px;
  text-align: center;
}
.subtitle {
  line-height: .9em;
  font-size: 5.5em;
  margin-top: 0;
  margin-bottom: 40px;
}
.tagline {
  font-size: 1.4em;
  line-height: 1.3em;
  font-weight: normal;
  text-align: center;
}
.thumbnail {
  background-color: rgba(255, 255, 255, .2);
  border: 0 none;
  padding: 10px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
}
.thumbnail .caption {
  color: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons">
  <a class="btn" id="about">About</a>
  <a class="btn" id="work">My Work</a>
  <a class="btn" id="contact">Contact</a>
</div>


<!-- Main (Home) section -->
<section class="section" id="about">
  <div class="container">
    <div class="person" style="display: block;">
      <div class="row">
        <div class="col-md-10 col-lg-10 col-md-offset-1 col-lg-offset-1 text-center">

          <!-- Site Title, your name, HELLO msg, etc. -->
          <h1 class="title">Welcome!</h1>
          <h2 class="subtitle">My name is Daniel Adamek</h2>

          <!-- Short introductory (optional) -->
          <h3 class="tagline">
I am 23 years old IT enthusiast located in Zlin, Czech Republic.<br>
Currently, I am looking for any kind of job in IT field.<br>
          Please, check out my work and feel free to contact me :)
</h3>

          <!-- Nice place to describe your site in a sentence or two -->

        </div>
      </div>
      <!-- /col -->
    </div>
    <!-- /row -->

  </div>
</section>


<!-- Third (Works) section -->
<section class="section" id="work">
  <div class="container">
    <div class="thumbnail" style="display: block;">
      <h2 class="text-center title">More Themes</h2>
      <p class="lead text-center">
        Huge thank you to all people who publish
        <br>their photos at <a href="http://unsplash.com">Unsplash</a>, thank you guys!
      </p>
    </div>
    <div class="row">
      <div class="col-sm-4 col-sm-offset-2">
        <div class="thumbnail" style="display: block;">
          <img src="" alt="">
          <div class="caption">
            <h3>Thumbnail label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque doloribus enim vitae nam cupiditate eius at explicabo eaque facere iste.</p>
            <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
            </p>
          </div>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="thumbnail" style="display: block;">
          <img src="" alt="">
          <div class="caption">
            <h3>Thumbnail label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque doloribus enim vitae nam cupiditate eius at explicabo eaque facere iste.</p>
            <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
            </p>
          </div>
        </div>
      </div>
      <div class="col-sm-4 col-sm-offset-2">
        <div class="thumbnail" style="display: block;">
          <img src="" alt="">
          <div class="caption">
            <h3>Thumbnail label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque doloribus enim vitae nam cupiditate eius at explicabo eaque facere iste.</p>
            <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
            </p>
          </div>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="thumbnail" style="display: block;">
          <img src="" alt="">
          <div class="caption">
            <h3>Thumbnail label</h3>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque doloribus enim vitae nam cupiditate eius at explicabo eaque facere iste.</p>
            <p><a href="#" class="btn btn-primary" role="button">Button</a>  <a href="#" class="btn btn-default" role="button">Button</a>
            </p>
          </div>
        </div>
      </div>

    </div>

  </div>
</section>


To maintain the integrity of your existing HTML structure while enhancing functionality, you can implement the following JavaScript snippet:

$(document).ready(function(){
    $(".thumbnail").hide();
    $(".person").hide();
    $(".work").click(function(){
        $(".person").fadeOut('500');
        $(".thumbnail").delay('500').fadeIn('slow');      
    });
    $(".about").click(function(){
        $(".thumbnail").fadeOut('500');
        $(".person").delay('500').fadeIn('slow');      
    });
});

Answer №4

function hideAllItems()
{
    $(".hideable").hide();
}

$(document).ready(function(){
    hideAllItems();  // Start by hiding all items
    $(".button").click(function(){
        hideAllItems();
        if ($(this).hasClass("work"))
        {
          $(".thumbnail").fadeToggle('slow');
        }
        else if ($(this).hasClass("about"))
        {
           $(".person").fadeToggle('slow');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thumbnail hideable">thumbnail</div>
<div class="person hideable">person</div>

<button class="work button">Work</button>
<button class="about button">About</button> 

This code snippet serves as a starting point for handling click events on buttons with the .button class selector. It then determines the appropriate action based on the additional classes assigned to the button.

Answer №5

Your query does not require jQuery - it is all about using CSS to style and overlay two text elements. You can then apply fade in/out effects.

One suggestion would be to enclose both texts within a single div and adjust the position properties accordingly.

For example:

HTML

<div class="wrapper">
    <div class="thumbnail">Some Thumbnail</div>
    <div class="person">Some Person</div>
</div>

CSS

.wrapper {
    position: relative;
}

.wrapper div {
    position: absolute; //This will stack both divs on top of each other
}

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

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

State change shows the previous and current values simultaneously

I've been working on updating the values of initUsers on the DOM. The initial state values work fine, but when I try to update initUsers, it displays different values than expected. Essentially, entriesNum receives a number as an event and changes th ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

jquery mobile integrated seamlessly between image1 and image2

One issue I'm facing with jquery.mobile is that there seems to be a gap between photo1 and photo2 when displayed on my mobile device. Any suggestions on how to eliminate this space and have the images appear seamlessly next to each other? Thank you in ...

Can you identify the language of this HTML include code snippet?

Recently, I came across some .html files that include tags in a different format: [% INCLUDE '/path/to/footer.html' %] This bracket-and-percent-sign tag is unfamiliar to me. Does anyone know what it is used for? ...

Exploring the use of barcodes with node.js

Having some issues with generating a barcode using a barcode module from NPMJS called npm i barcode. I am getting an error message res is not defined even after following the instructions. Can someone please guide me in the right direction? Here is my code ...

What is the best way to retrieve the JQuery property from within a regular JavaScript function?

I am facing an issue with a function that takes an array as input and manipulates its values. The problem lies in the fact that the array is composed of JQuery nodes (specifically spans), and I retrieve the span value by utilizing the .text() method in jQu ...

Having trouble getting the Random Function to function correctly in Discord.js

I'm working on a piece of code that generates a random value to select two different values from two separate arrays. Every time I run it, however, the result seems to be the same and not truly random. I'm not sure where I went wrong with this. I ...

Working with a loop to handle the JQuery .change() event on a model containing a List of elements

I have created a View with cascading dropdown elements. When an element is selected from the first dropdown, it should populate the second dropdown with a list of resulting elements. This functionality works fine when I have just one pair of cascading drop ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on re ...

The AudioPlayer refuses to play following a track change

I am looking to implement an audio player in React Nextjs that features interactive dots, each representing an audio track. The functionality I want is such that clicking on a dot will pause the currently playing track (if any) and start playing the select ...

Paragraph Separated by Bullets Without Bullets At End of Line

I need assistance in creating a unique type of list that I call a "bullet separated paragraph list" by using a javascript array of strings. For example: item • item • item • item • item     item • item • item • item item • ...

What is the best way to ensure that table cells containing images resize without any issues?

I need help with centering and resizing an image on a screen. The image is divided into small images within cells, but I can't seem to get it right. Despite trying various solutions and spending hours resizing the table and images, the final output a ...

I am hoping for JavaScript to perform three distinct actions depending on the names of the files that are currently open in Photoshop

Currently, I am in the process of developing a JavaScript script for Photoshop. The main objective of this script is to prompt the user to choose a folder containing multiple files. Subsequently, the script will open each file within the folder and perform ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

The performance of the animation on http://responsive-nav.com/ becomes erratic when viewed on Android devices

Recently, I came across a fantastic plugin that works perfectly on regular computer browsers. However, when I tested it on my android phone, the css3 animation for the dropdown appeared choppy and seemed to be dropping frames. Does anyone have suggestions ...