"Enhancing User Experience with Dynamic Text Replacement through CSS and JavaScript

I'm currently working on implementing some unique features with JavaScript and CSS that I'm having trouble figuring out. Here's the progress I've made so far: http://codepen.io/melissall/pen/PPWPQE

  1. One of my goals is to center the headline within the image until the text starts scrolling up.

  2. I have a CSS transition in place that changes the color of the text, but I want it to be based on the position of the headline rather than time-based. To see an example of what I mean, check out how the logo changes color on this site:

I've tried searching for solutions online, but I haven't been able to find anything useful. If anyone could provide some guidance, I would greatly appreciate it.

Here's the code snippet:

HTML

<div id="image"></div>
<div id="container" class="row">
  <div id="heading" class="large-12">
    <h2>Heading lorem ipsum sit dolor</h2>
  </div>
  <div id="content" class="large-12">
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nisi ante, pulvinar a lorem id, pellentesque facilisis diam. Cras placerat libero ut urna auctor faucibus. Morbi facilisis diam et massa facilisis, vel vulputate ex malesuada. Fusce varius, ex id vulputate accumsan, arcu orci scelerisque purus, et tempor orci leo et nisi. Aliquam aliquet massa vel nibh dictum viverra. Mauris dapibus quam ut magna congue porttitor. Aenean suscipit tortor a urna dapibus dignissim. In ornare risus et mauris pellentesque pharetra. Nunc et ultrices erat. Maecenas interdum dignissim turpis, in porta erat. Donec tortor urna, finibus ut quam ac, aliquam ullamcorper arcu. Vivamus id est quis ante volutpat laoreet. Proin fringilla pharetra est a sagittis. Fusce non magna mauris. Proin iaculis aliquet mi, a pellentesque dui porttitor ac. </p>
  </div>
</div>

CSS

h2{
  color: #ffffff;
  font-size: 4em;
  font-weight: 700;
  font-family: 'Roboto Condensed', sans-serif;
}
#image  {
  background: url(http://7-themes.com/data_images/out/78/7039061-beautiful-tropical-beach-wallpaper.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 500px;
}
#heading{
  position: relative;
  top: -250px;
  text-transform: uppercase;
  color: #fff;  
}
#heading h2{
  color: #fff;
  padding-top: 20px;
}

#...

JS

var windw = this;

$.fn.followTo = function ( pos ) {
    var $this = this,
        $window = $(windw);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('#heading').followTo(490);

$(window).scroll(function() {
  var addRemClass = $(window).scrollTop() > 470 ? 'addClass' : 'removeClass';
    $("#heading h2")[addRemClass]('bgChange');
});

EDIT #1:

I managed to make some progress using just CSS, but encountered new issues. You can view the updated link here: http://codepen.io/melissall/pen/pjRZdx

New Issue #1: The headline no longer stays above the text content. I had to remove the existing JS as it was causing conflicts with the positioning of the headline.

New Issue #2: If you scroll down far enough, the white text that was overlaying the image reappears.

EDIT #2: I was able to resolve the issues (at least on CodePen) by adding additional JS code that detects when a specific point on the page is reached and adjusts the positions of the heading and content accordingly. The code may not be perfect, but it meets the basic functionality requirements I set out to achieve. Here's the final version of the code for reference: http://codepen.io/melissall/pen/pjRZdx

Answer №1

Have you ever heard of Parallax? Check it out here: https://github.com/wagerfield/parallax

The website you mentioned seems to be using the same concept.

I visited the link you shared and noticed that there are 2 images:

It appears that instead of changing the logo color, he is changing the entire image.

For more examples of websites with top 50 parallax effects, check out this list:

Hopefully my response sheds some light on your query.

Answer №2

You have the option to incorporate various CSS styles and utilize jQuery scroll to activate the style based on specified conditions.

body{}
h2{
  color: #ffffff;
  font-size: 5em;
  font-weight: 700;
  text-transform: uppercase;
  font-family: 'Roboto Condensed', sans-serif;
  height: 5em;
}
#image  {
  background: url(http://7-themes.com/data_images/out/78/7039061-beautiful-tropical-beach-wallpaper.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 500px;
}


#content{
  padding-top: 100px;
}


.heading {
  position: absolute;
  height: 100%;
  border: 1px solid red;
  clip: rect(0, auto, auto, 0);
}

.copy.pink {
  position: fixed;
  top: 100px;
  color: pink;
}
/* Added this line to stick once its in the content */
.copy.pink.stick {
      position: static;
    display: block;
    width: 100%;
}

.copy.white {
    position: fixed;
    top: 100px;
    color: white;
}
/* Added this line to hide white copy once its in the content */
.copy.white.hidden {
  display:none;
}

JS

// Get distance of copy white from top
var whitedistance      = $('.copy.white').offset().top;
$( window ).scroll(function() {
  //Get distance of copy pink on top
  var wscrollTop     = $(window).scrollTop(),
    pinkOffset = $('.heading').offset().top,
    pinkdistance      = (pinkOffset - wscrollTop);
  console.log(pinkdistance + " == " + whitedistance)
// if distance of pink is less than or equal the height and the white is still visible add class hidden to hide it.
  if(pinkdistance <= whitedistance && !$('.copy.white').hasClass('hidden') ){
    console.log('hidden');
    $( ".copy.white" ).addClass( "hidden" );
    $( ".copy.pink" ).addClass( "stick" );
  }
  else if(pinkdistance > whitedistance && $('.copy.white').hasClass('hidden')){
// Display copy white again once the distance of copy pink is higher again than the white
    $( ".copy.white" ).removeClass( "hidden" );
    $( ".copy.pink" ).removeClass( "stick" );
  }
});

I trust this solution will be effective for your needs. :)

Answer №3

If you're working on a similar project and need the final code, check it out here: http://codepen.io/melissall/pen/pjRZdx

HTML

<div id="image"></div>
<div id="container" class="row">
  <h2 class="copy white large-9">Heading Here</h2>
    <div class="heading large-9">
        <h2 class="copy pink large-9">Heading Here</h2>
    </div>
  <div id="content" class="large-12">
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nisi ante, pulvinar a lorem id, pellentesque facilisis diam. Cras placerat libero ut urna auctor faucibus. Morbi facilisis diam et massa facilisis, vel vulputate ex malesuada. Fusce varius, ex id vulputate accumsan, arcu orci scelerisque purus, et tempor orci leo et nisi. Aliquam aliquet massa vel nibh dictum viverra. Mauris dapibus quam ut magna congue porttitor. Aenean suscipit tortor a urna dapibus dignissim. In ornare ri...uttae dignissim turpis, in porta erat. Donec tortor urna, finibus ut quam ac, aliquam ullamcorper arcu. Vivamus id est quis ante volutpat laoreet. Proin fringilla pharetra est a sagittis. Fusce non magna mauris. Proin iaculis aliquet mi, a pellentesque dui porttitor ac. </p>
</div>

CSS

body{}
h2{
  color: #ffffff;
  font-size: 5em;
  font-weight: 700;
  text-transform: uppercase;
  font-family: 'Roboto Condensed', sans-serif;
}
#image  {
  background: url(http://7-themes.com/data_images/out/78/7039061-beautiful-tropical-beach-wallpaper.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 500px;
}
#content{
  padding-top: 100px;
}
.heading {
  position: absolute;
  height: 100%;
  border: 1px solid red;
  clip: rect(0, auto, auto, 0);
}
.copy.pink {
  position: fixed;
  top: 100px;
  color: pink;
}
.copy.white {
    position: fixed;
    top: 100px;
    color: white;    
}
.unstuck-copy{
  position: absolute !important;
  border: 1px solid blue;
  top: 0px !important;
  width: 100%;
}
.unstuck-heading{
  position: relative !important;
  border: 1px solid pink;
  width: 100%;
  height: 100%
}

JS

// Hide the white text after scrolling past the image
$(window).scroll(function() {
    if ($(this).scrollTop()>350){
        $('.white').hide();
    }else{
        $('.white').show();
    }
});

$(window).scroll(function() {
    if ($(window).scrollTop() > 400) {
        $('.heading').addClass('unstuck-heading');
        $('.copy.pink').addClass('unstuck-copy');
    } else {
        $('.heading').removeClass('unstuck-heading');
      $('.copy.pink').removeClass('unstuck-copy');

    }
});

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 you provide steps on arranging two divs in a side by side layout

I need assistance with aligning two divs next to each other, both containing images. The goal is for the divs to remain side by side and for the images to automatically resize based on the screen size. When the screen size is reduced, I want the images t ...

In Firebase within the Next.js framework, encountering an error where the property 'length' of an undefined element cannot be read

I am encountering an issue with Firebase in Next.js, displaying the error message: TypeError: Cannot read property 'length' of undefined Is there a way to resolve this error? Below is my Firebase configuration file: import * as firebase from &q ...

Using a semicolon right after "id" is recognized as an unexpected token

I encountered an issue while attempting to run my express.js program. The main server fails to start and displays the following error message. id; ^ SyntaxError: Unexpected token ; at new Script (vm.js:80:7) at createScript (vm.js:274:10) ...

The functionality of $watch is not functioning correctly within the Modal, despite implementing it with $scope.user={pwd1:''}

For the Plunker link referenced, please click here: http://plnkr.co/edit/0vOjw0?p=preview index.html <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css"> ...

"Can anyone explain why my plugin is displaying the error message 'Definition for rule was not found'

Introducing my custom plugin You can find the plugin here: @bluelovers/eslint-plugin For the base config, visit: https://github.com/bluelovers/ws-node-bluelovers/blob/master/packages/eslintrc/.eslintrc.json When it comes to the runtime user config: { ...

I do not send JSON Express post for receiving

I have a question regarding sending JSON data to my Express server using request. However, when Express receives the data, it doesn't seem to be in the correct JSON format. Below, I will share the code related to this issue. The JSON I am sending ...

What are the best methods for encoding and decoding query parameters?

Here is the current implementation of my Express.js function "Restore objects pickled into JSON strings": router.post('/restore', json_parser, function(request, response, next) { console.log('router.post /load'); console.log(&apo ...

Issue with updating a div using jQuery ajax and adding fresh content

How can I update the content of the #calendar div with new data from calendar.php? Although I receive a success alert, the content does not refresh. What adjustments can I make to display the new calendar.php data that was posted? $(document).ready(functi ...

Avoid triggering the onClick event on multiple submit buttons when the form data is deemed invalid by vee-validate

How can I ensure that the onClick event on a button is only called if certain input fields are valid, using vee-validate ValidationObserver? The validation should apply to individual buttons within a form, rather than the entire form itself, as there are m ...

Ways to position an absolute element in the middle of two CSS Grid cells

Is it possible to position an element with position: absolute between two grid cells, where half of the element is on the sidebar and the other half is on the rest of the page? The challenge arises when there is overflow set on both the sidebar and the pag ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

What exactly is the function of registerServiceWorker in React JS?

Just starting out with React and I have a question about the function of registerServiceWorker() in this code snippet: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServi ...

Using Vue to display a Div inside a TD element of a table does not result in a reactive behavior

I am encountering an issue with a table where the last column contains a div with three options (View, Edit, and Delete). This submenu is initially hidden, but when clicking on the options button in the last column of the table, the array used to control i ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Is it possible to activate a block display for an article based on the class value when a radio

Here is the HTML code snippet I'm working with: <div id="contentapp"> <input type="radio" name="menu" id="interest" checked> <input type="radio" name="menu" id="about"> <div id="tab"> <label for="intere ...

Obtain a segment of the string pathway

In this scenario, there is a file path provided below. Unlike the rest of the URL, the last part (referred to as video2.mp4) regularly changes. The language used for this project is either Javascript or Typescript. file:///data/user/0/com.sleep.app/files/ ...

Using jQuery to retrieve an element's Id by its class name

Within my dynamic HTML generated by jQuery, I have the following code snippet: <tr id="CustomerScreen" class="rows"></tr> <tr id="TraderScreen" class="rows"></tr> <tr id="DistributorScreen" class="rows"></tr> I want to ...

Looking for a way to conduct a recursive search in a Javascript object that fits your specific requirements?

Hello there, I'm currently developing a text-based game using Javascript. In my code, I have a variable called map which is an object containing information about different rooms in the game. I found an algorithm that I would like to modify for my sp ...

Reactjs application encounters an "err_connection_refused" error when attempting to connect to a Nodejs backend hosted on different network

I am currently developing an App with a Reactjs front end and node.js back end. The application runs smoothly on the server machine, but when I attempt to access it using localhost:4000 on a different machine connected to the same network, the front end fu ...