jquery loop to create a border highlight effect

I'm struggling to create a loop that will smoothly transition the border color of an image from black to yellow and back again over a set number of seconds. Additionally, I want the loop to stop when the image is clicked on. I feel like I might not be using the correct tools for this task and could use some guidance on how to approach it. Any suggestions would be greatly appreciated!

Here is what I have attempted so far, but if there is a more efficient method, please let me know!

for (i = 100; i >= 0; i--) {
    $("#imgid").css("border-color", 'rgb(' + i + '%,' + i + '%,0)');
}

There are a few specific things I'd like to learn about:

1.) I am unsure how to merge two loops in order to move both upwards and downwards, allowing the border color to transition between black and yellow continuously. Is this achievable with just one loop?

2.) How can I slow down the loop to control the speed at which the border color fades?

3.) What is the best way to terminate the loop using an onclick() event?

Answer №1

If you're looking to implement animations in your code, starting with the module pattern is a great idea. Below is a basic structure that includes the initial animation:

http://jsfiddle.net/Ue4wy/1/

I will also attempt to incorporate click interruptions, which can sometimes be challenging considering scope limitations.

[Edit]

Here is an updated version with the click functionality implemented successfully:

http://jsfiddle.net/Ue4wy/4/

[/Edit]

Code:

var anim = (function() {
    var i = 0;
    var step = 10;
    var up = true;
    var timer = null;

    var next = function() {
        if (up) {
            i += step;
        }
        else {
            i -= step;
        }
        if(i<0){i=0; up=true;}
        if(i>255){i=255; up=false;}
        update();
    };

    var update = function() {
        $("div").css("border-color", 'rgb(' + i + ',' + i + ',' + 0 + ')');
    };

    var go = function() {
        next();
        timer = window.setTimeout(anim.go, 30);
    };

    var stop = function() {
        if (timer) {
            window.clearTimeout(timer);
            timer = null;
        }
    };

    var addClickHandler = function() {
        $("div").click(function() {
            if(timer){
                anim.stop();
            }
            else{
                anim.go();
            }
        });
    };

    return {
        go: go,
        stop: stop,
        addClickHandler: addClickHandler 
    };
}());

anim.addClickHandler();
anim.go();

Answer №2

For those looking to implement a similar feature, check out this helpful resource:

To utilize the timer, simply use $.doTimeout in your code and keep track of the border's current state with a variable.

You can experiment with this functionality here: http://jsfiddle.net/JZ62H/4/ It is currently functioning as desired.

All the provided JavaScript comes from the initial link referenced above.

If you need to adjust the rate, simply modify the 2 in this line of code (it appears twice):

$.doTimeout('timerid', 2, doIt);

I also included a resume feature for added convenience.

Answer №3

Consider this demonstration:

for (i=0;i<=10;i++)
  {
  if (i==3)
    {
    break;
    }
  document.write("The number is " + i);
  document.write("<br />");
  }

Instead of i == 3 you can search for your specific condition...etc:
http://www.w3schools.com/jsref/event_onclick.asp

Also take a look at Creating Delays in JavaScript

Answer №4

Instead of creating animations from scratch, it is recommended to utilize jQuery's existing functionality:

  • jQuery provides .animate(), which:
  • allows for animating CSS properties,
  • includes options for animation speed,
  • enables callback functions upon completion of the animation,
  • although, it does not natively support color transitions; in such cases, you can integrate the color animation plugin (developed by jQuery's creator)

Utilizing these features, here's a sample implementation based on your requirements:

var stop = false; // flag to control animation interruption

function highlight() {
   // Animate border color to yellow over 1000 milliseconds
   $("#imgId").animate({borderColor: "yellow"}, 1000, function () {
      // Check if stop flag is set
      if (stop) return;
      // Transition back to black
      $("#imgId").animate({borderColor: "black"}, 1000, function () {
         // Continue animation cycle unless stop flag is triggered
         if (!stop) highlight();
      });
   });
}

// Initiate animation loop
highlight();

// Click event handler
$("#imgId").click(function () {
   stop = true;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an HTML element is deleted, its events are not being removed as expected

I currently have events bound in my backbone view. sampleView = Backbone.View.extend({ events: { "click .sum": "sumButtonFunc", "click .diff": "diffButtonFunc" } sumButtonFunc: function(){ console.log("sum called") ...

What is the best way to address a row of hyperlink text located at the top of a webpage?

I have encountered an issue where three rows of text links near the top of a page shift up to the very top when a link is pressed, causing them to obscure a line of text that was already at the top. How can I keep the position of these three rows anchored? ...

Bringing app templates and static files into Django templates

I am trying to include my gallery.html and gallery.css files within my base.html. After running the collectstatic and runserver commands, I am unable to locate the gallery.css and html files when inspecting with Chrome Dev Tools. Only the base.html and its ...

Calculate the minimum date that can be selected on a jQuery UI datepicker to be x years from

Good day I'm attempting to set the minimum date for a jQuery UI datepicker, restricting it to users aged between 12 and 17. While using maxDate alone works well, I need to calculate the minDate dynamically. Despite searching through multiple threads ...

Why doesn't the date appear in the Textbox when the TextMode is set to "Date"?

Within my application, there are three textboxes named tbEditStartDate, tbEditStopDate, and tbEditRenewalDate. These textboxes are used to display the start date, stop date, and renewal date of applicants in a Gridview called gvApp. I have implemented a Ro ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Having trouble getting my JS/CSS code to work for a single image music play/pause button. Any suggestions on how to fix it?

I'm currently working on a project and trying to incorporate a music button into the navigation bar. The goal is for the song to play when clicked, and then pause when clicked again. However, I've encountered some issues with getting it to functi ...

Creating a button that adjusts its size proportionally to the page and surrounding elements, all without relying on positioning

I'm fairly new to creating websites with CSS and HTML, and I'm currently working on a project about my time in China. The main issue I'm facing right now is aligning a button with my other contact icons and ensuring it scrolls correctly with ...

AngularJS failing to display HTML content is a common issue encountered

I am a beginner in Angular JS and recently wrote a simple Angular code. However, I am encountering issues with the HTML rendering incorrectly or the expressions not getting evaluated. I could use some help identifying what I might be missing. The version ...

Currently experiencing difficulties while attempting to create a Simon game in JavaScript. Seeking assistance to troubleshoot the issue

var buttonColor = ["red", "blue", "green", "yellow"]; var userClickedPattern = []; var gamePattern = []; var totalKey = []; var level = 0; $("*").on("keydown", function(m) { var key = m.key; totalKey.push(key); var keyLength = totalKey.leng ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

Is there a way to generate a SVG path connecting various DIV elements programmatically?

How can I achieve a dynamic SVG path between my word DIVs? This is my current progress and this is my desired outcome. Could you please explain why my code isn't working as expected? I attempted to calculate the XY positions of my words to create an ...

Function that can be shared between two separate jQuery files

Let's say I have two separate jQuery files, both containing the same function. I would like to create a common file where I can store this shared function and then import it into other files. For example: first.js file : window.addEventListener(&apo ...

Activate animation when hovering over an image within a container

I am attempting to create an animation that runs on one image inside a div when I hover over another image within the same div. However, it is not working as expected. The animation only takes effect when I use #div:hover, but not when I use #image:hover. ...

Issue with IE7 causing rollover navigation blocks to disappear when hovering over content

While conducting browser testing on the website The website's top navigation menu includes rollover effects for building services, exterior services, and commercial categories. The CSS-triggered navigation works seamlessly in all browsers except for ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

The division is refusing to make an appearance

As I embark on creating my very first website, I'm encountering some obstacles in translating my vision into reality. The #invokeryolo div is proving to be elusive and no matter how hard I try, I can't seem to make it appear on the screen. Below ...

Using Selenium with C# to input text into an HTML <input> tag is not functioning properly

I need help figuring out how to fill in an input field on a website using HTML. Here is what the section of the website () looks like: <div class="flex-item-fluid"> <input autocomplete="username" autocapitalize="off" ...

The essence of jQuery lies in its functionality

Is it possible to retrieve the innermost element that fulfills a 'contains' condition? If I have nested divs, my goal is to identify the final element rather than the parent: <div id="hayStack"> <div id="needle">Needle</div> ...

I'm experiencing some issues with the jQuery autocomplete functionality when implemented as a directive in AngularJS. It seems like there are some bugs that are

When attempting to implement autocomplete with an AngularJS directive, the plugin functions correctly. However, the code following the initialization of the directive does not work, and no errors are displayed. You can test it online here: http://jsbin.c ...