0

I've seen this question asked and answered before but after trying several proposed solutions I still haven't had any luck.

I have four buttons ( respectively with IDs "frst, prev, next, last,") None of them do anything when clicked. Currently the part of my code that isn't working looks like so:


const index = ['imgs/1.png', 'imgs/2.png', 'imgs/3.png', 'imgs/4.png', 'imgs/5.png'];

let current = index.length;

$(document).ready(function(){
   $(document).on('click', '#frst', function(){
        current = 1;
        funcUpdate();
    });

    $(document).on('click', '#prev', function(){
        current--;
        funcUpdate();
    });

    $(document).on('click', '#next', function(){
        current++;
            funcUpdate();
    });

    $(document).on('click', '#last', function(){
        current = index.length;
        funcUpdate();
    });

});

function funcUpdate() {
    $('#img').attr('src', index[current - 1]);;
    $('button').removeAttr('disabled');

    if (current == 1) {
        $('.back').attr('disabled', '1');
    }
    else if (current == index.length) {
        $('.frwd').attr('disabled', '1');
    }
}

My html looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="imgs.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    <body>
            <div>
                <img id="img" src="imgs/5.png"/>
                <div class="center">
                    <button type="button" class="back" id="frst">πŸž€πŸž€</button>
                    <button type="button" class="back" id="prev">πŸž€</button>
                    <button type="button" class="frwd" id="next">πŸž‚</button>
                    <button type="button" class="frwd" id="last">πŸž‚πŸž‚</button>
                </div>
            </div>
        </main>
     </body>
</html>

funcUpdate is meant to switch out the displayed image and disable buttons so you can't go outside the values currently in the array. When I don't use jQuery, like below, it works as intended.

<button class="back" onclick="funcFrst()">first</button>
<button class="back" onclick="funcPrev()">previous</button>
<button class="back" onclick="funcNext()">next</button>
<button class="back" onclick="funcLast()">last</button>

With code in imgs.js like so:

function funcFrst() {
    current = 1;
    funcUpdate();
}

function funcPrev() {
    current--;
    funcUpdate();
}

function funcNext() {
    current++;
    funcUpdate();
}

function funcLast() {
    current = index.length;
    funcUpdate();
}

In both cases, the js is in imgs.js.

I've also tried $('#ID').click and $('#ID').on('click', function(){});, each in and outside of $(document).ready with no luck. I've also seen it suggested to put the script below the buttons that call it, which also didn't work.

I bet it's probably some really obvious error I've overlooked but I figured I'd ask anyway.

5
  • 1
    Does this answer your question: $ is not defined (I already voted close as typo so can't revote)
    – fdomn-m
    Commented Apr 23, 2024 at 7:27
  • 1
    @fdomn-m yes, I I put the two scripts in the wrong order when you pointed it out
    – Julie Kelly
    Commented Apr 23, 2024 at 7:42
  • $(document).ready(function(){ $(document).on('click', '#frst', function(){ should be simply $(function(){ $('#frst').on('click', function(){ You want to hook the event handler to the element not the document. Commented Apr 23, 2024 at 11:48
  • @MarkSchultheiss hooking the event handler to the document is a standard option - it's event delegation (not needed in this case, so could rather than should)
    – fdomn-m
    Commented Apr 23, 2024 at 12:41
  • @fdomn-m I would beg to differ on that as attaching to document makes it traverse more of the DOM. Especially here where it is attaching multiple event handlers for no reason really. Better to attach to elements with an ID since that is a fast selector OR to the container if you are delegating so the traversal is smaller (I put that in my answer since that seems like it might be less code overall to do so). Commented Apr 23, 2024 at 20:13

2 Answers 2

0

a) You need to add the base jQuery library before any other third-party/local jQuery library file, then only your jQuery code will run. So swap the position of 2 js files added.

b) Instead of adding and removing, toggle the disabled property on the buttons

c) You need to modify funcUpdate() like below:

function funcUpdate(buttonObj) {
    $('#img').attr('src', index[current - 1]);
    $(".back").prop("disabled", function(i, val) {
        return (current == 1);
    });
    $('.frwd').prop("disabled", function(i, val) {
        return (current == index.length);
    });
}

Working snippet:

let current = 1;
const index = ['https://imageio.forbes.com/specials-images/imageserve/5faad4255239c9448d6c7bcd/Best-Animal-Photos-Contest--Close-Up-Of-baby-monkey/960x0.jpg?format=jpg&width=960', 'https://hips.hearstapps.com/hmg-prod/images/baby-animal-photos-65f9bc47971de.jpg', 'https://hips.hearstapps.com/hmg-prod/images/baby-animals-hedgehog-65f8af918f516.jpg?crop=0.6643126177024482xw:1xh;center,top&resize=980:*', 'https://cdn.firstcry.com/education/2022/11/26141737/Animal-Name-Starting-With-L-For-Kids.jpg', 'https://image.shutterstock.com/image-photo/two-little-funny-baby-goats-260nw-2140138487.jpg'];
$(document).ready(function() {
  $('#frst').click(function() {
    current = 1;
    funcUpdate();
  });

  $('#prev').click(function() {
    current--;
    funcUpdate();
  });

  $('#next').click(function() {
    current++;
    funcUpdate();
  });

  $('#last').click(function() {
    current = index.length;
    funcUpdate();
  });

});

function funcUpdate(buttonObj) {
  $('#img').attr('src', index[current - 1]);

  $(".back").prop("disabled", function(i, val) {
    return (current == 1);
  });
  $('.frwd').prop("disabled", function(i, val) {
    return (current == index.length);
  });
}
#img {
  height: 200px;
  width: 200px;
}
<!DOCTYPE html>
<html>

<head>
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script src="imgs.js"></script>
</head>

<body>
  <div>
    <img id="img" src="https://imageio.forbes.com/specials-images/imageserve/5faad4255239c9448d6c7bcd/Best-Animal-Photos-Contest--Close-Up-Of-baby-monkey/960x0.jpg?format=jpg&width=960" />
    <div class="center">
      <button type="button" class="back" id="frst">πŸž€πŸž€</button>
      <button type="button" class="back" id="prev">πŸž€</button>
      <button type="button" class="frwd" id="next">πŸž‚</button>
      <button type="button" class="frwd" id="last">πŸž‚πŸž‚</button>
    </div>
  </div>
  </main>
</body>

</html>

0
0

You were missing a start tag <main> so I added one. You can simplify the script to just account for however many images you have, trigger it on the first one to get started and just pass the function the current value.

Use .prop() for the disabled.

const index = ['imgs/1.png', 'imgs/2.png', 'imgs/3.png', 'imgs/4.png', 'imgs/5.png'];

$(function() {
  let current = index.length;
  $('.center').on('click','.direction', function(event) {
    const whichOne = $(this).index();
    // console.log(whichOne);
    switch (whichOne) {
      case 0:
        current = 0;
      case 1:
        current > 0 ? current-- : 0;
        break;
      case 2:
        current++;
        break;
      case 3:
        current = index.length - 1;
        break;
      default:
        current = 0;
    };
    funcUpdate(current, $(this).closest('.center'));
  }).find('.direction').eq(1).trigger('click'); // set up first one
});

function funcUpdate(current, $container) {
  $('#img').attr('src', index[current]);
  $('#img').attr('alt', index[current]);
  //console.log(index[current]);
  $container.find('button.direction').prop('disabled', false);
  $('.back').prop('disabled', current <= 0);
  $('.frwd').prop('disabled', current >= index.length - 1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<body>
  <main>
    <div>
      <img id="img" src="" alt="" />
      <div class="center">
        <button type="button" class="direction back" id="frst">πŸž€πŸž€</button>
        <button type="button" class="direction back" id="prev">πŸž€</button>
        <button type="button" class="direction frwd" id="next">πŸž‚</button>
        <button type="button" class="direction frwd" id="last">πŸž‚πŸž‚</button>
      </div>
    </div>
  </main>
</body>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.