jQuery(function ($) { var target = $("#target"); target.html(target.text().replace(/./g, "<span>$&</span>")); setTimeout(runAnimation, 250); function runAnimation() { var index, spans; index = 0; spans = target.children(); doOne(); function doOne() { var span = $(spans[index]); if (!$.trim(span.text())) { // Skip blanks next(); return; } // Do this one span.css({ position: "relative", }) .animate( { top: "-20", }, "fast" ) .animate( { top: "0", }, "fast", function () { span.css("position", ""); next(); } ); } function next() { ++index; if (index < spans.length) { doOne(); } else { setTimeout(runAnimation, 500); } } } });
.title { margin: auto; width: 50%; color: black; text-align: right; } #target:hover { color: rgb(21, 121, 252); animation-name: bounce; animation-duration: 2s; } @keyframes bounce { 0% { transform: translateY(0); } 50% { transform: translateY(-50px); } 100% { transform: translateY(0); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="title"> <p style="font-size: 45px;"><span id="target">I</span><span id="target">'</span><span id="target">m</span><span> </span><span id="target">K</span><span id="target">r</span><span id="target">i</span><span id="target">s</span> </p> </div>
I’m trying to add a wobble effect on each letter but I can’t get it to work, I would like the letters to get a bit bigger while hovering them and making the effect run. I’m just learning javascript so I’m not really good at it, the snippet doesn’t work and I don’t know what’s the problem with it. I found this code for the wobble effect but it’s not working, can someone help ? Thanks
Advertisement
Answer
Instead of manually typing the letters in individual span
blocks, let JavaScript do it. This will be much more flexible.
Other than that, you do not need to use JavaScript for the animation, do it with CSS instead. That will be much simpler and handleable.
const animatedElements = document.getElementsByClassName('animate'); [...animatedElements].forEach(elm => { let text = elm.innerText.split(''); // Split the text into letters and store them in an array elm.innerText = ''; // Clear the text in the div // Add the letters one by one, this time inside a <span> text.forEach(letter => { const span = document.createElement('span'); span.innerText = letter; elm.appendChild(span); }) })
.animate>span { display: inline-block; /* Changing display from the default `inline` to `inline-block` so that `transform` rules apply */ white-space: break-spaces; /* This is necessary so that the `inline-block` does not collapse the "spaces" */ transition: transform 200ms ease-in-out; } .animate>span:hover { transform: translateY(-10px); } /* The following rules are just to format the embedded result */ .animate { margin: 40px; font-size: 40px; }
<div class="animate"> I'm Kris </div>