JSFiddle - React, Tailwind, and code Playground

by kenji morita

HTML

<h1>When scrolling to a certain value, the function in which the element appears is executed</h1>
<main>

	<div id="target" class="dpn">to Top</div>
</main>
<script
		src="https://code.jquery.com/jquery-1.12.4.min.js"
		integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
		crossorigin="anonymous"></script>

<script>
	function debounce(fn, delay) {
		// maintain a timer
		let timer = null;
		// closure function that has access to timer
		return function() {
			// get the scope and parameters of the function
			// via 'this' and 'arguments'
			let context = this;
			let args = arguments;
			// if event is called, clear the timer and start over
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			}, delay);
		}
	}
	function add(){
			var obj_t_pos = $(window).scrollTop()
			if(obj_t_pos > 300){
				console.log(obj_t_pos);
				console.log("出現する", obj_t_pos)
				$('#target').addClass('db');
				$('#target').removeClass('dpn');

			}else{
				$('#target').addClass('dpn');
				$('#target').removeClass('db');
				console.log("消える")
			}
	}
	window.addEventListener('scroll', debounce(add, 200));
</script>

CSS

.red {
			color: red;
		}
		main {
			height: 2000px;
			background: #eae2e2;
		}
		ul {
			position: fixed;
			bottom: 0;
		}
		#target {
			position: fixed;
			bottom: 16px;
		}
		#target.db {
			display: block;
		}
		#target.dpn {
			display: none;
		}