简体   繁体   中英

How could I make this active onclick?

var span = document.getElementById('loading_dots');

var int = setInterval(function() {
    if ((span.innerHTML += '●').length == 4) 
        span.innerHTML = '';
}, 400);

(function(){
    var loading_dots = document.getElementById("loading_dots"),

      show = function(){
        loading_dots.style.display = "block";
        setTimeout(hide, 5000); // 5 seconds
      },

      hide = function(){
        loading_dots.style.display = "none";
      };

    show();
})();

How can I make it so loading_dots start on the click of a button, and re-activates everytime I click the button? the bottom function is to stop it after 5 seconds, maybe could merge it into one function?

Needs to work for 3 seperate buttons and relaunch on click of each, also needs to display inside of <span class="loading_dots" id="loading_dots"></span> any method is fine, css, jquery, or javascript

here is a jQuery version:

 (function ( $ ) { $.fn.loader = function( options ) { var settings = $.extend({ text:"●", spn: undefined }, options ); $.each(this, function(){ var btn = this; var int; var spn; if (settings.spn === undefined) { spn = $("<span/>" , { "class":"loading_dots" }); $(btn).append(spn); } else { spn= $(settings.spn); } var show = function(){ btn.setAttribute("disabled", "disabled") clearInterval(int); spn.show(); int = setInterval(function() { if ((spn[0].innerHTML += settings.text).length == 4) spn.html(""); }, 400); setTimeout(hide, 5000); // 5 seconds } var hide = function (){ spn.hide(); btn.removeAttribute("disabled", "disabled") clearInterval(int); } btn.addEventListener("click", show); }); }; }( jQuery )); // now bind it by its class, this only need to be run once every time new button is added to the html $(".btn").loader({spn:".loading_dots"}); // and you could also specify the text by // $(".btn").loader({text: "*"}); 
 .loading_dots { color:red; display:none; width:100%; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <span class="loading_dots"></span> <button class="btn" type="button" > submit </button> <button class="btn" type="button" > submit </button> </div> 

If you want to add an event listener for a button click, just select the buttons, and add the listeners in a loop:

document.querySelectorAll("button").forEach(e => e.addEventListener("click", myFunc));

Alternatively, listen for any click, then check if the event's target is a button:

document.addEventListener("click", (e) => if (e.target.tagName == "BUTTON") myFunc());

You could use CSS for the most part of your code, and than simply toggle a show class on the parent #loading element:

 const Loading = () => { let tOut = null; const el = document.querySelector("#loading"); const show = () => { el.classList.add('show'); tOut = setTimeout(hide, 5000); }; const hide = () => { el.classList.remove('show'); clearTimeout(tOut); }; return { show, hide }; }; const loadingDots = Loading(); const loadBtns = document.querySelectorAll('.load'); [...loadBtns].forEach(el => el.addEventListener('click', loadingDots.show)); // you can always use loadingDots.hide() to hide when needed (before the 5sec ticks out) 
 #loading { position: fixed; z-index: 100; top:0; left: 0; width:100vw; height:100vh; display:flex; background: rgba(0,0,0,0.5); color: #fff; font-size: 3em; align-items: center; justify-content:center; visibility: hidden; opacity: 0; transition: 0.4s; } #loading.show { opacity: 1; visibility: visible; } @keyframes blink { 50% {opacity: 1;} } #loading i:after {content: "\\25cf";} #loading i { opacity: 0; animation: blink 1.2s infinite; } #loading i:nth-child(2) { animation-delay: .2s; } #loading i:nth-child(3) { animation-delay: .4s; } 
 <div id="loading"><i></i><i></i><i></i></div> <button class="load">LOAD</button> <button class="load">LOAD</button> <button class="load">LOAD</button> 

A plain javascript version with the option to programmatically/manually stop displaying the loading dots. Just pass the id of the parent element you want the loading to be attached to. By default the loading will be appended to the parent but you can optionally pass an object as the last parameter with a position property.

 function removeLoading(id) { var parent = document.getElementById(id); var spans = parent.getElementsByClassName("loading_dots"); while (spans.length > 0) { var span = spans[0]; if (span.dataset.timerId) { clearTimeout(span.dataset.timerId); } span.remove(); } } function addLoading(id, options) { options = options || {}; var parent = document.getElementById(id); var existingSpans = parent.getElementsByClassName("loading_dots"); if (existingSpans.length > 0) { removeLoading(id); } var span = document.createElement("span"); span.setAttribute("class", "loading_dots"); if (options.timerId) { span.dataset.timerId = options.timerId; } parent.insertAdjacentElement(options.position || "beforeend", span); setInterval(function () { if ((span.innerHTML += '●').length == 4) span.innerHTML = ''; }, 400) } function addLoadingWithTimeout(id, ms, options) { options = options || {}; var timerId = setTimeout(function () { removeLoading(id) }, ms); options.timerId = timerId; addLoading(id, options); } 
 <p id="load1">Load 1 - Will stop automatically in 3 seconds after starting. </p> <button onclick="addLoadingWithTimeout('load1', 3000)">Start Load 1</button> <button onclick="removeLoading('load1')">Stop Load 1</button> <p id="load2">Load 2 - Only manual Stop </p> <button onclick="addLoading('load2')">Start Load 2</button> <button onclick="removeLoading('load2')">Stop Load 2</button> 

Here you go. on the HTML side, you just pass the event to the button that you want and then the id, as a string, of the span/div where you want the load icons to appear.

HTML:

  <button id="btn" onclick="load(event, 'loadDiv')">Load</button>
  <div>
    <span id="loadDiv"></span>    
  </div>

Below, we are getting the btn id from event so you don't have to manually pass it everytime. Then we are defining function for the innerhtml icons. Lastly, we are running the showIcon function every .4s and then clearing the interval after 5 seconds.

JS:

function load(e, location) {
  var btn = document.getElementById(e.srcElement.id)
  var loadDiv = document.getElementById(location)

  function showLoad() {
    if (loadDiv.innerHTML.length < 3) {
      return loadDiv.innerHTML += '●'
    }
    loadDiv.innerHTML = ''
  }

  (function() {
    var loadIcons = setInterval(function() {
      showLoad()
    }, 400)

    var clear = setTimeout(function() {
      clearInterval(loadIcons)
    }, 5000)
  })()
}

Hope this helps!

You can define your code in a function and add click handler to the button.

function myFunc() {
 var span = document.getElementById('loading_dots');

 var int = setInterval(function() {
     if ((span.innerHTML += '●').length == 4) 
         span.innerHTML = '';
 }, 400);

 (function(){
     var loading_dots = document.getElementById("loading_dots"),

       show = function(){
         loading_dots.style.display = "block";
         setTimeout(hide, 5000); // 5 seconds
       },

       hide = function(){
         loading_dots.style.display = "none";
       };

     show();
 })();
}

document.getElementById("myBtn1").addEventListener("click", myFunc); 
document.getElementById("myBtn2").addEventListener("click", myFunc); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM