Categories
JavaScript Web development

JavaScript Math.clz32()

JavaScript Math.clz32()

The JavaScript Math.clz32() is short for CountLeadingZeroes32, and it returns the number of leading zeros in a 32-bit binary representation of a number.

Syntax:

Math.clz32(x)

Example:

The number of leading zeros bits in the 32-bit binary representation of a number. If the number is 0, then this method returns 32 (as all bits are 0).

<!DOCTYPE html>
<html>
<body>

<button onclick="clz32Example()">Try it</button>

<p id="example"></p>

<script>
function clz32Example() {
  var a = Math.clz32(0);
  var b = Math.clz32(1);
  var c = Math.clz32(2);
  var d= Math.clz32(5);
  
  var x = a + "<br>" + b + "<br>" + c + "<br>" + d;
  document.getElementById("example").innerHTML = x;
}
</script>

</body>
</html>

Output:

Click the button to return the number of leading zeros in a 32-bit binary representation of different numbers:


Enjoy coding!

Categories
CSS Web development

How to create an expanding grid with CSS & JavaScript?

How to create an expanding grid with CSS & JavaScript?

To create an expanding grid with CSS & JavaScript follow the steps below:

Demo:

*click on the box to see the effect.

Step1.

Add HTML

<div class="col-container">
  <div class="column" onclick="tabExtend('aboutUs')" style="background-color:#2a9d8f;">
    About
  </div>
  <div class="column" onclick="tabExtend('services')" style="background-color:#e9c46a;">
    Services
  </div>
  <div class="column" onclick="tabExtend('contact')" style="background-color:#e76f51;">
    Contact
  </div>
</div>

<div id="aboutUs" class="expandedTab">
  <span onclick="this.parentElement.style.display='none'" class="close">&times;</span>
  <h2>About Us:</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eros metus, rhoncus eu dolor sed, scelerisque efficitur nunc. Nunc tempus risus porta nisi mollis consequat. Cras eu ultrices dui. </p>
</div>

<div id="services" class="expandedTab">
  <span onclick="this.parentElement.style.display='none'" class="close">&times;</span>
  <h2>Services:</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eros metus, rhoncus eu dolor sed, scelerisque efficitur nunc. Nunc tempus risus porta nisi mollis consequat. Cras eu ultrices dui. </p>
</div>

<div id="contact" class="expandedTab">
  <span onclick="this.parentElement.style.display='none'" class="close">&times;</span>
  <h2>Contact:</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eros metus, rhoncus eu dolor sed, scelerisque efficitur nunc. Nunc tempus risus porta nisi mollis consequat. Cras eu ultrices dui. </p>
</div>

Step2.

Add CSS

* {
  box-sizing: border-box;
}

body {
  margin: 0;
}

.column {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  float: left;
  width: 33.33%;
  padding: 70px;
  font-size: 30px;
  cursor: pointer;
  color: white;
}

.expandedTab {
  padding: 70px;
  color: white;
}

.col-container:after {
  content: "";
  display: table;
  clear: both;
}

.close {
  float: right;
  color: white;
  font-size: 35px;
  cursor: pointer;
}

#aboutUs, #services, #conact {
  display: none;
}

#aboutUs {
  background-color:#2a9d8f;
}

#services {
  background-color:#e9c46a;
}

#contact {
  background-color:#e76f51;
}

p {
  font-size: 20px;
}

Step3.

Add JavaScript

function tabExtend(name) {
  var i, x;
  x = document.getElementsByClassName("expandedTab");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(name).style.display = "block";
}

Enjoy coding!

Categories
CSS HTML JavaScript Web development

Scroll To Top Button (smooth scroll effect)

smooth scroll effect

To learn how to create the Button – Scroll To Top with the smooth scroll effect, follow the steps below:

Demo:

Step1.

Add HTML

Create the text container and add some text and the button:

<div class="content">
<div class="text"><h1 class="heading">Scroll Down</h1>
<p>He  was  an  old  man  who  fished  alone  in  a  skiff  in  the  Gulf  Stream  and  he  had  gone  eighty-four days now without taking a fish. In the first forty days a boy had been with him. But  after  forty  days  without  a  fish  the  boy’s  parents  had  told  him  that  the  old  man  was  now definitely and finally salao, which is the worst form of unlucky, and the boy had gone at  their  orders  in  another  boat  which  caught  three  good  fish  the  first  week.  It  made  the  boy  sad  to  see  the  old  man  come  in  each  day  with  his  skiff  empty  and  he  always  went  down to help him carry either the coiled lines  or  the  gaff  and  harpoon  and  the  sail  that  was  furled  around  the  mast.  The  sail  was  patched  with  flour  sacks and, furled, it looked like the flag of permanent defeat.   The  old  man  was  thin  and  gaunt  with  deep  wrinkles  in  the  back  of  his  neck.  The  brown blotches of the benevolent skin cancer the sun brings from its [9] reflection on the tropic  sea  were  on  his  cheeks.  The  blotches  ran  well  down  the  sides  of  his  face  and  his  hands  had  the  deep-creased  scars  from  handling  heavy  fish  on  the  cords.  But  none  of  these scars were fresh. They were as old as erosions in a fishless desert.   Everything  about  him  was  old  except  his  eyes  and  they  were  the  same  color  as  the  sea and were cheerful and undefeated.   “Santiago,”  the  boy  said  to  him  as  they  climbed  the  bank  from  where  the  skiff  was  hauled up. “I could go with you again. We’ve made some money.”   The old man had taught the boy to fish and the boy loved him.   “No,” the old man said. “You’re with a lucky boat. Stay with them.”   “But remember how you went eighty-seven days without fish and then we caught big ones every day for three weeks.”   
  </p>
<p>“I remember,” the old man said. “I know you did not leave me because you doubted.”   “It was papa made me leave. I am a boy and I must obey him.”   “I know,” the old man said. “It is quite normal.”   “He hasn’t much faith.”   [10] “No,” the old man said. “But we have. Haven’t we?”   “Yes,”  the  boy  said.  “Can  I  offer  you  a  beer  on  the  Terrace  and  then  we’ll  take  the  stuff  home.”    “Why not?” the old man said. “Between fishermen.”   They sat on the Terrace and many of the fishermen made fun of the old man and he was noteangry. Others, of the older fishermen, looked at him and were sad. But they did not  show  it  and  they  spoke  politely  about  the  current  and  the  depths  they  had  drifted  their  lines  at  and  the  steady  good  weather  and  of  what  they  had  seen.  The  successful  fishermen  of  that  day  were  already  in  and  had  butchered  their  marlin  out  and  carried  them laid full length across two planks, with two men staggering at the end of each plank, to  the  fish  house  where  they  waited  for  the  ice  truck  to  carry  them  to  the  market  in  Havana. Those who had caught sharks had taken them to the shark factory on the other side of the cove where they were hoisted on a block and tackle, their livers removed, their fins cut off and their hides skinned out and their flesh cut into strips for salting.   When  the  wind  was  in  the  east  a  smell  came  across  the  harbour  from  the  shark  factory;  but  today  there  [11]  was  only  the  faint  edge  of  the  odour  because  the  wind  had  backed into the north and then dropped off and it was pleasant and sunny on the Terrace.</p>
  <p>“Santiago,” the boy said. “Yes,” the old man said. He was holding his glass and thinking of many years ago.   “Can I go out to get sardines for you for tomorrow?”   “No. Go and play baseball. I can still row and Rogelio will throw the net.”   “I would like to go. If I cannot fish with you. I would like to serve in some way.”   “You bought me a beer,” the old man said. “You are already a man.”   “How old was I when you first took me in a boat?”   “Five and you nearly were killed when I brought the fish in too green and he nearly tore the boat to pieces. Can you remember?”   “I  can  remember  the  tail  slapping  and  banging  and  the  thwart  breaking  and  the  noise of the clubbing. I can remember you throwing me into the bow where the wet coiled lines  were  and  feeling  the  whole  boat  shiver  and  the  noise  of  you  clubbing  him  like  chopping a tree down and the sweet blood smell all over me.”   [12] “Can you really remember that or did I just tell it to you?”</p>
</div>
<button onclick='window.goUp({top: 0, behavior: "smooth"});' id="top">Top</button>
  </div>

Step2.

Add CSS

Set the position of the background and elements:

body {
  display: flex;
  justify-content: center;
}

.content {
  position: relative;
  display: flex;
  justify-content: center;
}

Style the text:

.heading {
  text-align: center;
  position: relative;
}

.text {
  width:50%;
  font-size: 20px;
  padding: 20px 50px;
}

Style the button:

#top {
  position: fixed;
  bottom: 40px;
  background-color: #264653;
  padding: 20px;
  border-radius: 20px;
  border: none;
  color: white;
  font-weight: bold;
  left:80%;
  cursor: pointer;
  display: none;
  transition: .2s;
}

#top:hover {
  background-color: #2a9d8f;
}

#top:active {
  background-color: #e76f51;
}

Add CSS @media rule (to display text and the effect on the small screens):

@media only screen and (max-width: 600px) {
  .text {
    font-size: 15px;
  }
}

Step3.

Add JavaScript

const button = document.getElementById("top");

window.onscroll = function() {showButton()};

function showButton() {
  if (document.body.scrollTop > 25 || document.documentElement.scrollTop > 25) {
    button.style.display = "block";
  } else {
    button.style.display = "none";
  }
}

function goUp() {
window.scrollTo({top: 0, behavior: 'smooth'});
}

Enjoy coding!

Categories
CSS HTML JavaScript Web development

Scroll Indicator

Scroll Indicator

To create the CSS & JavaScript Scroll Indicator follow the steps below:

Demo:

Step1.

Add HTML

<div class="content"><h1>Scroll Down</h1>
<div class="scroll-indicator">
  <div id="scroll-bar" class="scroll-bar"></div>
  </div>
    </div>
  <div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin egestas quis lorem vitae placerat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut et commodo ex, non porttitor dui. Vestibulum quis sem tincidunt, lobortis lectus id, fermentum elit. Cras ut justo pulvinar, iaculis massa nec, consectetur magna. Integer in posuere neque, in efficitur nunc. Etiam porta rutrum dignissim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Suspendisse placerat at ipsum a finibus. Quisque in facilisis risus. In quis justo et lectus tincidunt auctor. Nunc metus justo, iaculis eu ultricies at, eleifend id dolor. Proin et commodo augue. Aliquam euismod ac augue eu dapibus. Quisque suscipit urna nunc, id ultrices justo volutpat at. Vivamus bibendum lacus vitae est egestas fermentum. Cras viverra, magna eget fermentum rhoncus, nisl velit pharetra est, at elementum lorem velit at odio. Fusce ac pharetra turpis. Fusce hendrerit vulputate nunc, non auctor leo auctor at. Fusce cursus posuere diam sed hendrerit. Nullam dignissim tellus ut tristique mollis.

Vivamus non urna lectus. Quisque fermentum, nisi convallis vulputate malesuada, turpis leo ultrices enim, vel gravida purus enim a lorem. Sed nec tellus neque. Nullam risus sem, semper eu ullamcorper nec, tincidunt at arcu. Integer leo velit, maximus ac lectus sed, porta suscipit felis. Aliquam elementum in mauris vel iaculis. Cras auctor commodo nulla, at imperdiet orci sollicitudin quis. Vivamus semper sem et arcu mattis, at congue augue tempor.

In nec arcu in libero rutrum pellentesque nec vel ipsum. Duis scelerisque ex nulla, vel dignissim turpis tristique eget. Nullam vitae malesuada velit. Vivamus pellentesque posuere posuere. Quisque gravida sit amet quam id viverra. Fusce nec placerat purus. Suspendisse enim elit, rutrum eu rhoncus vitae, dictum et enim. Morbi et venenatis diam. Donec eget diam in neque dictum sodales. Aenean pharetra dictum tristique. Ut at ultrices odio, consectetur tempor purus. Nullam laoreet quis odio quis tincidunt. Phasellus nec augue eu ante placerat molestie vel a lacus. Nulla accumsan tempus libero id mollis. Etiam a elit non enim posuere tempus ac consectetur nunc. Proin sollicitudin facilisis mi.
    
In nec arcu in libero rutrum pellentesque nec vel ipsum. Duis scelerisque ex nulla, vel dignissim turpis tristique eget. Nullam vitae malesuada velit. Vivamus pellentesque posuere posuere. Quisque gravida sit amet quam id viverra. Fusce nec placerat purus. Suspendisse enim elit, rutrum eu rhoncus vitae, dictum et enim. Morbi et venenatis diam. Donec eget diam in neque dictum sodales. Aenean pharetra dictum tristique. Ut at ultrices odio, consectetur tempor purus. Nullam laoreet quis odio quis tincidunt. Phasellus nec augue eu ante placerat molestie vel a lacus. Nulla accumsan tempus libero id mollis. Etiam a elit non enim posuere tempus ac consectetur nunc. Proin sollicitudin facilisis mi.

Nullam molestie, purus quis cursus cursus, magna turpis finibus eros, a ultrices turpis velit in leo. Maecenas auctor lacinia nisi, ac rhoncus velit finibus ac. Quisque ac velit efficitur nunc facilisis dignissim ac a ipsum. Vestibulum porttitor eu odio eu vehicula. Suspendisse ac fringilla ligula. In tincidunt sem eget elit vehicula, ac ullamcorper odio consectetur. Suspendisse quis nulla sed dui tincidunt viverra. Mauris accumsan sagittis sapien. Suspendisse urna purus, fringilla eu purus eget, pellentesque elementum velit. Praesent nec pretium arcu.Nullam molestie, purus quis cursus cursus, magna turpis finibus eros, a ultrices turpis velit in leo. Maecenas auctor lacinia nisi, ac rhoncus velit finibus ac. Quisque ac velit efficitur nunc facilisis dignissim ac a ipsum. Vestibulum porttitor eu odio eu vehicula. Suspendisse ac fringilla ligula. In tincidunt sem eget elit vehicula, ac ullamcorper odio consectetur. Suspendisse quis nulla sed dui tincidunt viverra. Mauris accumsan sagittis sapien. Suspendisse urna purus, fringilla eu purus eget, pellentesque elementum velit. Praesent nec pretium arcu.
  </div>

Step2.

Add CSS

Style the scroll bar and the text:

.content {
  position: fixed;
  top: 0;
  z-index: 1;
  width:100%;
  text-align: center;
  background-color: #264653;
  color: white;
}

.scroll-indicator {
  width: 100%;
  height: 10px;
  background-color: #2a9d8f;
}

.scroll-bar {
  height: 10px;
  background-color: #e9c46a;
  width: 0%;
}

.text {
  width:50%;
  font-size: 25px;
  position: relative;
  left:26%;
  padding:110px 0;
}

Step3.

Add JavaScript

window.addEventListener('scroll',()=> scrollBar())

function scrollBar() {
  var scrollDown = document.body.scrollTop || document.documentElement.scrollTop;
  var h = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scroll = (scrollDown / h) * 100;
  document.getElementById("scroll-bar").style.width = scroll + "%";
}

Enjoy coding!

Categories
CSS JavaScript Web development

Countdown Timer

Countdown Timer

To learn how to create the Countdown Timer follow the steps below:

Demo:

Step1.

Add HTML

<div class="countdown-container">
  <h1 id="christmasTime">Let's countdown to Christmas!</h1>
  <div id="countdown">
    <ul>
      <li><span id="d"></span>Days</li>
      <li><span id="hr"></span>Hours</li>
      <li><span id="min"></span>Minutes</li>
      <li><span id="sec"></span>Seconds</li>
    </ul>
  </div>
  <div id="fest" class="emoji">
    <span>🎄</span>
    <span>🎅</span>
    <span>🎁</span>
  </div>
</div>

Step2.

Add CSS

Set the colour and the position of the background and elements:

body {
  background-color: #006d77;
  justify-content: center;
  align-items: center;
  display: flex;
  height: 100vh;
}

Style the countdown container:

.countdown-container {
   position: relative;
   color: white;
}

h1 {
  letter-spacing:7px;
}

li {
  display: inline-block;
  font-size: 20px;
  list-style-type: none;
  padding: 35px;
  text-align: center;

}

li span {
  display: block;
  font-size: 4.5rem;
}

.emoji {
  display: none;
  padding: 35px;
}

.emoji span {
  font-size: 4rem;
  padding: 20px;
}

Add @media rule (to display on small screen devices):

@media only screen and (max-width: 450px) {
  h1 {
    font-size: 30px;
  }
  
  li {
    font-size: 30px;
    padding: 20px;
    text-align: center;
  }
  
  li span {
    font-size: 30px;
  }
}

Enjoy coding!

Categories
CSS Web development

Read More/ Read Less Button

Read More/ Read Less Button

To create the CSS & JavaScript Read More/ Less button follow the steps below:

Demo:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra scelerisque orci, eu laoreet tortor euismod quis. Sed id volutpat magna. Suspendisse porta nisi eget massa accumsan, nec tempus est consectetur. Nam quis quam volutpat, luctus massa interdum, dictum metus. Etiam ut scelerisque ante. Quisque quam sem nulla. Quisque quam sem, porttitor eu finibus in, consequat quis sapien. Maecenas id fermentum lorem. Nulla vitae mattis justo, non dictum velit. Phasellus sit amet lorem viverra, sagittis neque id, volutpat leo. Curabitur purus elit, tincidunt nec commodo a, sollicitudin eu ipsum. Suspendisse pulvinar tincidunt nisl.


Step1.

Add HTML

Add some text and the button:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra scelerisque orci, eu laoreet tortor euismod quis. Sed id volutpat magna. Suspendisse porta nisi eget massa accumsan, nec tempus est consectetur. Nam quis quam volutpat, luctus massa interdum, dictum metus. Etiam ut scelerisque ante. Quisque quam sem <span id="sep">...</span><span id="moreText">nulla. Quisque quam sem, porttitor eu finibus in, consequat quis sapien. Maecenas id fermentum lorem. Nulla vitae mattis justo, non dictum velit. Phasellus sit amet lorem viverra, sagittis neque id, volutpat leo. Curabitur purus elit, tincidunt nec commodo a, sollicitudin eu ipsum. Suspendisse pulvinar tincidunt nisl. </span></p>

<button onclick="readMoreLess()" id="button">Read more</button>

Step2.

Add CSS

#moreText {display: none;}

Step3.

Add JavaScript

function readMoreLess() {
  var sep = document.getElementById("sep");
  var moreText = document.getElementById("moreText");
  var buttonText = document.getElementById("button");

  if (sep.style.display === "none") {
    sep.style.display = "inline";
    buttonText.innerHTML = "Read More"; 
    moreText.style.display = "none";
  } else {
    sep.style.display = "none";
    buttonText.innerHTML = "Read Less"; 
    moreText.style.display = "inline";
  }
}

Enjoy coding!

Categories
JavaScript Web development

JavaScript Math.asin() & Math.asinh()

JavaScript Math.asin() & Math.asinh()

The JavaScript Math.asin() returns the arcsine of a number as a value between -PI/2 and PI/2 radians.

Syntax:

Math.asin(x)

Example:

<!DOCTYPE html>
<html>
<body>

<button onclick="asinExample()">Try it</button>
<p id="ex-1"></p>

<script>
function asinExample() {
  document.getElementById("ex-1").innerHTML = Math.asin(0.7);
}
</script>

</body>
</html>

Output:

Click the button to display the arcsine of 0.7


Note: If the parameter x is outside the range -1 to 1, the browser will return NaN.

The JavaScript Math.asinh() returns the hyperbolic arcsine of a number.

Syntax:

Math.asinh(x)

Example:

<!DOCTYPE html>
<html>
<body>

<button onclick="asinhExample()">Try it</button>
<p id="ex-2"></p>

<script>
function asinhExample() {
  document.getElementById("ex-2").innerHTML = Math.asinh(1);
}
</script>

</body>
</html>

Output:

Click the button to display the hyperbolic arcsine of 1


Enjoy coding!

Categories
JavaScript Web development

JavaScript Math.acosh()

JavaScript Math.acosh()

The JavaScript Math.acosh() returns the hyperbolic arccosine of a number.

Syntax:

Math.acosh(x)

Example:

<!DOCTYPE html>
<html>
<body>

<button onclick="acoshExample()">Try it</button>
<p id="ex-1"></p>

<script>
function acoshExample() {
  document.getElementById("ex-1").innerHTML = Math.acosh(2);
}
</script>

</body>
</html>

Output:

Click the button to display the hyperbolic arccosine of 2


If the x is less than 1, the method will return NaN:

<!DOCTYPE html>
<html>
<body>

<button onclick="acoshNan)">Try it</button>
<p id="ex-2"></p>

<script>
function acoshNan() {
  document.getElementById("ex-2").innerHTML = Math.acosh(0.7);
}
</script>

</body>
</html>

Output:

Click the button to display the hyperbolic arccosine of 0.7


Enjoy coding!

Categories
CSS JavaScript Web development

CSS & JavaScript Image Magnifier Glass

Image Magnifier Glass

Demo:

*to see the Magnifier Glass effect on the website click here.

To create the CSS & JavaScript Image Magnifier Glass follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript

Step1.

Add HTML

Create the image container and add the image that you want to Magnifique:

<div class="image-container">
  <img id="dinant" src="https://lenadesign.org/wp-content/uploads/2021/06/image-mg.jpg" width="600" height="440">
</div>

Step2.

Add CSS

Set the color and the position of the background and elements:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.image-container {
  position:relative;
}

Style the image:

#dinant {
  border: 10px solid #333;
  box-shadow: 0 0 20px rgba(0,0,0,0.6);
}

And add magnifying glass:

.magnifier-glass {
  position: absolute;
  border: 5px solid #333;
  border-radius: 50%;
  cursor: none;
  width: 100px;
  height: 100px;
}

.magnifier-glass:before {
  content:"";
  position: absolute;
  width: 15px;
  height:70px;
  border-radius: 30px;
  background-color: #333;
  top:86px;
  left:90px;
  transform: rotate(-33deg);
}

Step3.

Add JavaScript

function Zoom(img, zoom) {
  var img, loupe, width, height, back;
  img = document.getElementById("dinant");

  loupe = document.createElement("div");
  loupe.setAttribute("class", "magnifier-glass");

  img.parentElement.insertBefore(loupe, img);
  loupe.style.backgroundImage = "url('" + img.src + "')";
  loupe.style.backgroundRepeat = "no-repeat";
  loupe.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
  back = 2;
  width = loupe.offsetWidth / 2;
  height = loupe.offsetHeight / 2;

  loupe.addEventListener("mousemove", moveLoupe);
  img.addEventListener("mousemove", moveLoupe);
  loupe.addEventListener("touchmove", moveLoupe);
  img.addEventListener("touchmove", moveLoupe);
  
  function moveLoupe(e) {
    var pos, x, y;

    e.preventDefault();

    pos = position(e);
    x = pos.x;
    y = pos.y;

    if (x > img.width - (width / zoom)) {x = img.width - (width / zoom);}
    if (x < width / zoom) {x = width / zoom;}
    if (y > img.height - (height / zoom)) {y = img.height - (height / zoom);}
    if (y < height / zoom) {y = height / zoom;}

    loupe.style.left = (x - width) + "px";
    loupe.style.top = (y - height) + "px";
    loupe.style.backgroundPosition = "-" + ((x * zoom) - width + back) + "px -" + ((y * zoom) - height + back) + "px";
  }
  function position(e) {
    var a, x = 0, y = 0;
    e = e || window.event;

    a = img.getBoundingClientRect();
    x = e.pageX - a.left;
    y = e.pageY - a.top;

    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {x : x, y : y};
  }
}

Zoom("dinant", 2);

Enjoy coding!

Categories
CSS JavaScript JQuery Web development

Div (circle) follows the cursor

Div follows the cursor

Demo:

*to see the “circle follows the cursor” on the website click here.

To create the “div/ circle that follows the cursor” follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript/ jQuery

Step1.

Add HTML

<div class="circle"></div>

Step2.

Add CSS

.circle {
	position: absolute;
  border: solid 4px #333;
	width: 65px; 
	height: 65px; 
  border-radius: 50%; 
  transition: .15s;
}

.circle:active {
  border: solid 4px #e76f51;
}

Step3.

Add JavaScript /jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Tip: Don’t forget to add jQuery library in the <head> section!

var Y = 0, X = 0;
var moveY = 0, moveX = 0;
   
$(document).mousemove(function(event){
    Y = event.pageY - 33; 
    X = event.pageX - 33;
  });
    
setInterval(function(){
    moveY += ((Y - moveY)/15);
    moveX += ((X - moveX)/15);
    $(".circle").css({ top: moveY +'px', left: moveX +'px'});
  }, 0);

Enjoy coding!