Categories
Development jQuery

How can I loop variables with Jquery

I’m new with Javascript and Jquery and I’m facing a small problem.

I’m trying to make sure that if a given link exists, hovering over this link will bring up a popup with the fadeToggle().

So I wrote this code that works:

  if ($('.link-1')) {
    $('.link-1').mouseover(function () {
      $('.popup-1').fadeToggle();
    })
      .mouseout(function () {
        $('.popup-1').fadeToggle();
      })
  }

But, instead of repeating it ten times, I wanted to write a loop, like this:

  var number = 0;
  while (number < 10) {
    var popup = '.popup-' + number;
    var link = '.link-' + number;
    if ($(link)) {
      $(link).mouseover(function () {
        $(popup).fadeToggle();
      })
        .mouseout(function () {
          $(popup).fadeToggle();
        })
    }
    number++;
  }

But it does not work. Could you help me please ?

I thank you in advance !

Leave a Reply

Your email address will not be published. Required fields are marked *