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

Remove any list items that do not possess a particular class

My ul list contains several lis, and I need to remove all li elements that do not have children with the class noremove. This is the original HTML: <ul> <li>Item 1</li> <li>Item 2 <ul> <li>I ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

When the if-else statement is executed, it showcases two strings:

Learning Experience: Unveiling My Lack of Cleverness Update: It appears that utilizing PHP in my current setup is not possible. As a result, I'll take some time to contemplate while banging my head against a wall. Despite that, thank you all for your ...

The act of splicing an array in React causes continuous rerendering

Within the update(changeProps) function, my code resembles the following: update(changedProps) { if (this.person) { this.__arr = ['hi', 'hi', 'hi']; } else { this.__arr = ['bye', &apos ...

The most effective way to code overlapping html buttons

Can you help me figure out how to make clickable areas on my HTML5 web page without them overlapping? Here's what I'm trying to do: I want the red, blue, and green areas to be clickable links, but not overlap. For example, when clicking on the f ...

retrieve the value obtained from a promise in an outer scope

I need a simple function that returns the name. Here's my existing code snippet: getName(entity, id) { const promise = userServices.getName(entity, id).then((data) => { return data; }); / ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Tips for concealing dynamically generated div elements within a VueJS v-for loop

Is there a way to hide dynamically generated div elements in VueJS? In my chatbot application, messages are passed through a prop called messages. These message arrays create multiple Divs on the screen displaying information. One particular Div is used to ...

JavaScript filename

This question may appear simple, but I believe the answer is not as straightforward. Here it goes: Should I keep the filename of jQuery as "jquery-1.3.2.min.js" for compatibility reasons, or should I rename it to jquery.js? In my opinion, it's best ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...

Tips for removing the Y-Axis entirely from a CanavasJS chart

I'm working with a canvasJS chart and my goal is to completely hide the Y-Axis. I've managed to remove the Y-Axis line and title in this JSFiddle example. I came across these properties to hide the Y-Axis title and line, but I'm struggling t ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Ways to present information for selecting an option from an AJAX post response and displaying it in Laravel

Is there a reason why the information from ajax POST is not being displayed in the offerDropdown option? Although console.log(el.devc_name) displays correctly in the browser console. <form method="POST" name="formSellout" id=&quo ...

Enhancing productivity with tools for developers and effortless tab navigation

During my development process, I always keep the developer tools open on one or more of my tabs. However, I noticed that when I switch to a tab where the developer tools were not previously open, a resize event is triggered. Strangely, this event causes el ...

Preventing Page Scroll While New Data is Loading

I am currently working on a React class component that uses Post components. Within this component, there is a button that triggers the loading of more data from the database. The issue I am encountering is that when new data is fetched, the page automatic ...

adjust the dimensions of the clickable icon's background

Is there a way to expand the pressable area of a close icon without altering its size? For example, if the icon is 19X19 pixels, can the pressable area be increased to 39X39 pixels? The concern lies with the div element containing the close button and the ...

Manipulate DIVs by sliding them and resizing their contents with JQuery

Can someone help me with sliding the top div up and down, and the left div left and right? I wrote some code for this but seem to be facing some issues. When I slide the left div, the center content falls down momentarily. Additionally, the code doesn&apos ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

"Troubleshooting: Why isn't the ParamQuery Jquery Grid plugin showing

I have a specific requirement to present data in a grid format with pagination, and it will be read-only, so no editing functionality is needed. After exploring various plugins, I came across the ParamQuery Grid from jQuery which seems to fit my needs perf ...