Run Function only when div appears

Asked

Viewed 2,726 times

2

Hello guys I have an accountant and I wanted it to start when the div #time starts to appear on the screen

<script type="text/javascript">
        $(document).ready(function (){
            $('.spincrement').spincrement({
                from: 0.0,
                decimalPlaces:0 ,
                duration: 5000,
            });
        });
    </script>

JS DO PLUGIM

/**
 * jQuery Spincrement plugin
 *
 * Plugin structure based on: http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html
 * Leveraging of jQuery animate() based on: http://www.bennadel.com/blog/2007-Using-jQuery-s-animate-Method-To-Power-Easing-Based-Iteration.htm
 * Easing function from jQuery Easing plugin: http://gsgd.co.uk/sandbox/jquery/easing/
 * Thousands separator code: http://www.webmasterworld.com/forum91/8.htm
 *
 * @author John J. Camilleri
 * @version 1.2
 */

/* global jQuery */

(function ($) {
  // Custom easing function
  $.extend($.easing, {
    // This is ripped directly from the jQuery easing plugin (easeOutExpo), from: http://gsgd.co.uk/sandbox/jquery/easing/
    spincrementEasing: function (x, t, b, c, d) {
      return (t === d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b
    }
  })

  // Spincrement function
  $.fn.spincrement = function (opts) {
    // Default values
    var defaults = {
      from: 0,
      to: null,
      decimalPlaces: null,
      decimalPoint: '.',
      duration: 1000, // ms; TOTAL length animation
      leeway: 50, // percent of duraion
      easing: 'spincrementEasing',
      fade: true,
      complete: null
    }
    var options = $.extend(defaults, opts)

    // Function for formatting number
    var re_thouSep = new RegExp(/^(-?[0-9]+)([0-9]{3})/)
    function format (num, dp) {
      num = num.toFixed(dp) // converts to string!

      // Non "." decimal point
      if ((dp > 0) && (options.decimalPoint !== '.')) {
        num = num.replace('.', options.decimalPoint)
      }

      // Thousands separator
      if (options.thousandSeparator) {
        while (re_thouSep.test(num)) {
          num = num.replace(re_thouSep, '$1' + options.thousandSeparator + '$2')
        }
      }
      return num
    }

    // Apply to each matching item
    return this.each(function () {
      // Get handle on current obj
      var obj = $(this)

      // Set params FOR THIS ELEM
      var from = options.from
      if (obj.attr('data-from')) {
        from = parseFloat(obj.attr('data-from'))
      }

      var to
      if (obj.attr('data-to')) {
        to = parseFloat(obj.attr('data-to'))
      } else if (options.to !== null) {
        to = options.to
      } else {
        var re = new RegExp(options.thousandSeparator, 'g')
        to = parseFloat(obj.text().replace(re, ''))
      }

      var duration = options.duration
      if (options.leeway) {
        // If leeway is set, randomise duration a little
        duration += Math.round(options.duration * ((Math.random() * 2) - 1) * options.leeway / 100)
      }

      var dp
      if (obj.attr('data-dp')) {
        dp = parseInt(obj.attr('data-dp'), 10)
      } else if (options.decimalPlaces !== null) {
        dp = options.decimalPlaces
      } else {
        var ix = obj.text().indexOf(options.decimalPoint)
        dp = (ix > -1) ? obj.text().length - (ix + 1) : 0
      }

      // Start
      obj.css('counter', from)
      if (options.fade) obj.css('opacity', 0)
      obj.animate(
        {
          counter: to,
          opacity: 1
        },
        {
          easing: options.easing,
          duration: duration,

          // Invoke the callback for each step.
          step: function (progress) {
            obj.html(format(progress * to, dp))
          },
          complete: function () {
            // Cleanup
            obj.css('counter', null)
            obj.html(format(to, dp))

            // user's callback
            if (options.complete) {
              options.complete(obj)
            }
          }
        }
      )
    })
  }
})(jQuery)

MY DIV:

    <div id="horario">
        <div id="img-horario">
            <div class="wrap4">
                <ul>
                    <li class="liH2" style="margin-right: 145px;">
                         <img src="images/hora/02.png">
                        <h1 class="spincrement">1454</h1>
                        <h2 style="margin-left: 13px;">HORAS TRABALHADAS</h2>
                    </li>
                    <li class="liH2" style="margin-right: 145px;margin-top: 14px;">
                         <img src="images/hora/03.png">
                        <h1 class="spincrement">489463</h1>
                        <h2 style="margin-left: 8px;">PROJETOS FINALIZADOS</h2></li>
                    <li class="liH2" style="margin-right: 145px;margin-top: 21px;">
                          <img src="images/hora/01.png">
                        <h1 class="spincrement">56464</h1>
                        <h2 style="margin-left: 12px;">METROS DE IMPRESSÃO</h2></li>
                    <li class="liH2" style="margin-top: -3px;">
                        <img src="images/hora/04.png">
                        <h1 class="spincrement">18500</h1>
                        <h2 style="margin-left: 30px;">XÍCARAS DE CAFÉ</h2></li>
                </ul></div></div></div>

2 answers

1

Call the jQuery.ready of your div and not of the document.

$("#divHorario").ready(function (){
  $('.spincrement').spincrement({
    from: 0.0,
    decimalPlaces:0 ,
    duration: 5000,
  });
});

Using the jQuery.show()

$("#divHorario").show(function (){
  $('.spincrement').spincrement({
    from: 0.0,
    decimalPlaces:0 ,
    duration: 5000,
  });
});

By default leave your div hide and at the moment you want to show it use the show and pass as parameter in the function the behavior you want.

  • already tried it didn’t work either, the animation for if I put DIV instead of Document

  • Shows an error or feedback in the console?

  • sorry I said wrong, it does the same way as with Document, the page loading it already starts animation, and no error appears on the console

  • This event will only be triggered when the div has uploaded. If you are displaying your div at the time you create the document, the div will be "started" right after the page load. Try to explain in your question in more detail what you are doing and what the expected result.

  • The TIME div already carries with the page, is where the animation will take place. THIS ANIMATION is just to do the numbers that are inside the UL LI of the div #horario that are with the class . spincrement INCREASE UNTIL THE NUMBER I PUT.

  • I suggest you use the function jQuery.show sometime in the load of your page and pass a function in the function. See the example in jsFiddle

  • the animation to... if I leave it hidden it does not show when it goes down to the div.

  • I don’t know how to help you =/. As I said before, fill in more details of what you’re doing, what you need, the more details the easier someone tries to help you. You can edit your question and put whatever you think is necessary.

  • got it... but it’s just something easy that’s not going. .

Show 4 more comments

0

I think it works

 $('.spincrement').spincrement({
          from: 0.0,
          decimalPlaces:0 ,
          duration: 5000,
          complete: function (e) {
             alert('Faz algo ao aparecer a DIV')
          }
 });
  • Stopped the animation like that:

  • Elaborate more on what happened.

  • Inside a div I have the animation of the spincrement, where makes the numbers make animation of how it was increasing until the number I put. But I want this animation to begin only when the div appears on the screen

  • The spincrement plugin does not have this option?

  • I couldn’t find

  • @kaiquemix Atualizei, give a look.

  • so it works with the normal that I posted, but it starts the animation as soon as the page loads and not when the div appears on the screen.

  • with . bind animation does not work or Alert.

  • If this way doesn’t work, then I don’t know.,

  • Okay, thanks for the help buddy :)

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.