5

Hello I got a question regarding changing a text after a user scrolled the page.

How can I change the text of my h1 from YES to NO when a user scrolled?I have tried several things like .append(), .html() but with no succes.

My code: JSFIDDLE

HTML

<h1>YES</h1>

<article style="height: 1000px">
    <p>test</p>
</article>

JS

$(document).ready(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            //change yes to no
        } else {
            //set h1 text to yes
        }
    });
});

The reason I want this is because in the case of using .html(), I can add inline html objects like: .html('<span>yes</span>')

AndrewRalon
  • 496
  • 1
  • 9
  • 24
Rotan075
  • 2,567
  • 5
  • 32
  • 54

4 Answers4

8

try this

the WORKING FIDLE

$(document).ready(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) { 
            //change yes to no
            $('h1').html('No');
        } else {
            //set h1 text to yes
            $('h1').html('Yes');
        }
    });
});
Vishnu Prasad
  • 729
  • 1
  • 11
  • 28
4

try this

<h1 id="h1">YES</h1>


$(document).ready(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
            $("#h1").text("NO");
            //change yes to no
        } else {
            $("#h1").text("YES");

            //set h1 text to yes
        }
    });
});
Pradeep Kumar
  • 4,065
  • 2
  • 33
  • 40
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
  • 1
    You shouldn't really have to add an ID/Class to the H1, as you are only supposed to have one on a page – Geert Aug 18 '15 at 13:01
3

You can try this with much optimized code:

$(window).scroll(function() {
  $('h1').html($(this).scrollTop() > 100 ? 'Yes':'No');
}).scroll(); //<---triggers the scroll on load
body{height:1200px;}
h1{position:fixed;} /* <---for example only i positioned it fixed.*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
Jai
  • 74,255
  • 12
  • 74
  • 103
2

You can make yours element position fixed and then try this logic

HTML

<h1 id="yy" style="position:fixed">YES</h1>

<article style="height: 1000px">
    <p>test</p>
</article>

Jquery

$(document).ready(function () {

    $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
           $("#yy").text("NO")
        } else {
            $("#yy").text("YES")
        }
    });
});

JSFIDDEL

Hope it will help

Roli Agrawal
  • 2,356
  • 3
  • 23
  • 28