Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display animation based on link # extension

Is it possible to set jQuery up to catch a # link and display an animation based on which one it picks up?

Example:

Click Link 1 > /index.php#1 = pulsate div 1

Click Link 2 > /index.php#2 = pulsate div 2

Click Link 3 > /index.php#3 = pulsate div 3

I currently have a guide/rule page, and it want it to highlight the correct content when people are taken there by a specific link. I understand basic jQuery animations, just not giving them rules from a parent page.

like image 291
James Lawson Avatar asked Nov 28 '25 23:11

James Lawson


2 Answers

1. Read hash from URI

JS's window.location.hash will read the hash like "#1" which is a valid ID in HTML5

jQuery(function($) {
   $( window.location.hash ).addClass("pulsate");
});

where you have DIV elements like

<div id="div1">I'm DIV 1</div>

and a CSS class like

.pulsate {
  /* other styles here... */
  animation: pulsate 0.5s ease-in-out;
  animation-iteration-count: 5;                                    /* Pulsate 5 times */
}
@keyframes pulsate {
  0%    {transform: scale(1);}
  50%   {transform: scale(1.2);}
}

2. Read hash from clicked link

If you're not interested in reading the URI's hash but you have simply LInks like

<a class="animateButton" href="#div1">Animate DIV1</a>

than this is all you need:

$(".animateButton").on("click", function(){
  $( this.hash ).addClass("pulsate").on("animationend", function(){
    $(this).removeClass("pulsate");
  });
});
.pulsate {
  background: orange;
  animation: pulsate 0.5s ease-in-out;
  transition:0.5s;
  animation-iteration-count: 3; 
}
@-webkit-keyframes pulsate {
  0%    {transform: scale(1);}
  50%  {transform: scale(1.1);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="animateButton" href="#1">#1</a>
<a class="animateButton" href="#2">#2</a>
<a class="animateButton" href="#3">#3</a>

<div id="1">I'm DIV #1</div>
<div id="2">I'm DIV #2</div>
<div id="3">I'm DIV #3</div>
like image 51
Roko C. Buljan Avatar answered Dec 01 '25 14:12

Roko C. Buljan


It's not rules "from a parent page". You can get the hash parameter from a page's url by using location.hash:

//index.php#1
location.hash //-> will return #1

//index.php#2
location.hash //-> will return #2

Then, you can select it directly in your jQuery selector as $(location.hash). This will enable you to animate the targeted div.

$(document).ready(function() {
    //Do your animation
    $(location.hash).animate(/*...*/)
});

obs:

Remember that divs with numeric ids are only valid in HTML5

like image 26
LcSalazar Avatar answered Dec 01 '25 12:12

LcSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!