Polymer: Issues with cycling through pages using the "Prev" or "Next" buttons

I am currently developing a Polymer app and facing an issue with writing my script in a declarative manner. I keep encountering the error message

Uncaught ReferenceError: selectedTestimonial is not defined

In addition, the code restricts the array to only 3 items (0,1,2), but I need it to allow for an infinite number of items.

The problematic code section is as follows:

<script>

    Polymer({
      is: "page-testimonials",

      properties: {
          selectedTestimonial: {
              type: Number,
              value: 0
          },
      },

      _PrevClick: function() {
          selectedTestimonial = selectedTestimonial === 0 ? 2 : (selectedTestimonial - 1);
      },

      _NextClick: function() {
          selectedTestimonial = selectedTestimonial === 2 ? 0 : (selectedTestimonial + 1);
      }


    });

</script>

Below is the complete code for your reference:

    <!--
    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
        TESTIMONIALS (page)
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->
    <link rel="import" href="../../bower_components/polymer/polymer.html">
    <link rel="import" href="../components/component-page.html">


    <dom-module id="page-testimonials">
    <template>

        <style>
        :host {
            display: block;
            width: 100%;
            height: 100%;
            box-sizing: border-box;
        }

        component-page {  }

        iron-swipeable-pages { z-index: 1; }
        iron-swipeable-pages > * {
            padding: 2rem;
            -webkit-user-select: none;  /* Chrome all / Safari all */
            -moz-user-select: none;     /* Firefox all */
            -ms-user-select: none;      /* IE 10+ */
            user-select: none;          /* Likely future */
            cursor: default;
        }
        .page { height: 100%; }

        img {
            border-radius: 100%;
            -webkit-backface-visibility: hidden;
            outline: transparent solid 1px;
            border: 12px solid rgba(0, 0, 0, .25);
        }

        h3 { color: rgba(246, 255, 140, 1); font-size: 2rem; font-weight: 300; text-transform: uppercase; padding: 1rem 0 0; }
        h4 { color: rgba(246, 255, 140, .5); font-size: 15px; font-weight: 300; text-transform: uppercase; opacity: .48; position: relative; }
        h4::after { content: ""; display: block; width: 200%; height: 3px; background: rgba(0, 0, 0, .25); position: absolute; top: calc(100% + 10px); left: -50%; }
        p { color: #fff; position: relative; z-index: 1; font-size: 1rem; font-weight: 100; margin: 1rem 78px; padding: 1rem 0; }

        .next-click,
        .prev-click {
            color: rgba(255, 255, 255, .25);
            position: absolute;
            top: calc(50% - 40px);
            z-index: 10;
        }

        .prev-click { left: 0; }
        .next-click { right: 0; }



    @media (min-width: 769px) {
        img { border: 22px solid rgba(0, 0, 0, .25) }
        h4::after { height: 2px; }
        p {  }
        .next-click,
        .prev-click {
            color: rgba(255, 255, 255, .25);
            position: absolute;
            top: calc(50% - 70px);
            z-index: 10;
        }
        .prev-click { left: 50px; }
        .next-click { right: 50px; }
    }

        </style>


        <!--  Content
        ---------------------------------------------------------------------------------------------------------------->
            <component-page grid="vertical" layout="start-center" min-height="1">

                <!-- Arrows -->
                <paper-icon-button class="prev-click" mobile-size="72" tablet-size="112" desktop-size="150" icon="hardware:keyboard-arrow-left" on-click="_PrevClick"></paper-icon-button>
                <paper-icon-button class="next-click" mobile-size="72" tablet-size="112" desktop-size="150" icon="hardware:keyboard-arrow-right" on-click="_NextClick"></paper-icon-button>


                <!-- Testimonial -->
                <iron-swipeable-pages on-selected-changed="_onSelectedChanged" selected="{{selectedTestimonial}}" flex="1" width="100" show-arrow>
                    <div class="page" grid="vertical" layout="center-center">
                        <img src="https://randomuser.me/api/portraits/men/7.jpg" size="300" mobile-size="150">
                        <h3>Justin O'Neill</h3>
                        <h4>Beaumont, Texas</h4>
                        <p mobile-width=".8" tablet-width=".75" desktop-width=".5" desktop-max-width="600px">This company is top notch, on task, and gets the job done! Clearly outstanding, honest, and reliable in work and service--AND a reasonable price! The estimate bid was on the money exactly.</p>
                    </div>

                    <div class="page" grid="vertical" layout="center-center">
                        <img src="https://randomuser.me/api/portraits/men/17.jpg" size="300" mobile-size="150">
                        <h3>Justin O'Neill</h3>
                        <h4>Beaumont, Texas</h4>
                        <p mobile-width=".8" tablet-width=".75" desktop-width=".5" desktop-max-width="600px">This company is top notch, on task, and gets the job done! Clearly outstanding, honest, and reliable in work and service--AND a reasonable price! The estimate bid was on the money exactly.</p>
                    </div>

                    <div class="page" grid="vertical" layout="center-center">
                        <img src="https://randomuser.me/api/portraits/men/27.jpg" size="300" mobile-size="150">
                        <h3>Justin O'Neill</h3>
                        <h4>Beaumont, Texas</h4>
                        <p mobile-width=".8" tablet-width=".75" desktop-width=".5" desktop-max-width="600px">This company is top notch, on task, and gets the job done! Clearly outstanding, honest, and reliable in work and service--AND a reasonable price! The estimate bid was on the money exactly.</p>
                    </div>
                </iron-swipeable-pages>


                <fx-skew bg="white"></fx-skew>
            </component-page>
        <!--  Content
        ---------------------------------------------------------------------------------------------------------------->


    </template>



    <script>

        Polymer({
          is: "page-testimonials",

          properties: {
              selectedTestimonial: {
                  type: Number,
                  value: 0
              },
          },

          _PrevClick: function() {
              selectedTestimonial = selectedTestimonial === 0 ? 2 : (selectedTestimonial - 1);
          },

          _NextClick: function() {
              selectedTestimonial = selectedTestimonial === 2 ? 0 : (selectedTestimonial + 1);
          }


        });

    </script>

    </dom-module>

Answer №1

When accessing properties, remember to use this.PROPERTYNAME (e.g., this.selectedTestimonial). To make the max index dynamic instead of hard-coded, you can determine it by inspecting all <iron-swipeable-pages> for page divs and getting the length of the result.

Polymer({
  is: "page-testimonials",

  properties: {
    selectedTestimonial: {
      type: Number,
      value: 0
    },
  },

  _PrevClick: function() {
    // assuming <iron-swipeable-pages id="swipe">
    var pages = this.$.swipe.querySelectorAll('.page');
    var max = (pages && pages.length - 1) || 0;
    this.selectedTestimonial = this.selectedTestimonial === 0 ? max : (this.selectedTestimonial - 1);
  },

  _NextClick: function() {
    // assuming <iron-swipeable-pages id="swipe">
    var pages = this.$.swipe.querySelectorAll('.page');
    var max = (pages && pages.length - 1) || 0;
    this.selectedTestimonial = this.selectedTestimonial === max ? 0 : (this.selectedTestimonial + 1);
  }
});

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

Press the "Enter" key to automatically submit the form and validate the input

How can I make my form submit when the "enter" key is pressed? Currently, I have set the button type as "submit" so that the form is submitted when enter is pressed. However, I also want to call a function with validation and confirmation. Right now, it&ap ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Different method of including the ng-click attribute on the body element

Greetings! I am currently developing a chrome extension and incorporating Angular to prevent any conflicts with other Angular pages. To avoid conflicts, I am attempting to set an ng-click on the body element. Here is the code snippet I used: var body = do ...

Calculating remaining change with the modulus operator in JavaScript

I have a task where I need to convert any given number of pennies into the correct amount of Quarters, Dimes, Nickels, and leftover pennies. My program currently uses Math.floor() to calculate the total value of each respective coin type when executed in ...

Retrieving data in batches using HTTP in JavaScript

My RESTful service has the capability to batch requests, which I am attempting to do using the Fetch API: let req1 = { url: "/cups/count", options: { method: 'GET', headers: { 'Content-Ty ...

Avoiding duplication of prints in EJS template files

In my EJS code, I have created a loop to fetch the total amount of items from the database. Here is my current code: <h2>Summary</h2> <% if(typeof items.cart!=="undefined"){ var amount = 0; %> <% i ...

Is it possible for an <input> tag in PHP AJAX to have an "action" attribute similar to a <form> tag?

Forms typically use an action attribute to specify where the data should be posted, such as a .php file. Do <input> elements have this action attribute as well? The answer is likely no, but I am curious to understand what concept I may be misunders ...

React-router-dom causing component not to render

I am currently working on setting up different components to render on different routes within my application. Here is a snippet from my index.js file: ReactDOM.render(<Routes />, document.getElementById('root')); The render function in m ...

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

The AngularJS $filter(date) function is causing incorrect format outputs

Hey there! I've come across an issue with my AngularJS filter, where it's supposed to return a date in a specific format. However, when I try the following code: var input = '2015-08-11T13:00:00'; var format = 'yyyy MMM dd - hh:mm ...

Cycle through different models using three.js graphical user interface

I have a scene with multiple models and I am using dat.gui to toggle through them. Previously, I attempted to achieve this by toggling the visibility on/off with the following code: var gui = new dat.GUI(); var controls = { toggleObjects: function(){ g ...

Split an array into N chunks using Numpy

Recently, I came across a discussion on how to split a list into evenly sized chunks in Python. I'm curious if there are more efficient ways to accomplish this task for large arrays using Numpy? ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

What is the process for importing files in a Firefox extension (add-on)?

We have developed browser extensions for Chrome, Firefox, and Safari. The Firefox extension includes a tracker called tracker.js, which is accessed from the controller using this line of code: tracker = require("../../firefox/tracker.js").tracker; The tr ...

Ways to determine if the property of a document has been altered?

Currently, I am in the process of writing tests for an Express CRUD application. The specific route I am focused on is the account recovery route. This route accepts POST requests with an email included in the body. Essentially, the application will search ...

Unexpected behavior encountered when using onClick in a material-ui List component containing Buttons

Looking to implement a customized list using React and Material-UI, where each item features a Checkbox, a text label, and a button. The onClick event for the Checkbox should be managed by a separate function from the onClick event for the Button. Encount ...

What seems to be the issue with the functionality of the done button?

I am currently working on developing a to-do list application where I can add and remove tasks. Adding tasks is functioning correctly, but when it comes to clicking the Done Button, it's not performing as expected. This issue indicates a logical error ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? https://i.sstatic.net/mEEMS.jpg HTML <label><span class="r ...

Invisible Dropdown Feature in Google Places Autocomplete

On my website, I have a Google Places autocomplete feature that seems to be fully functional, but it is not visible. Surprisingly, I know that it is working because when I type in "123 Main Street" and then navigate down using the arrow key and press enter ...

Dividing a 2D numpy array into sections using row as the basis

After converting a block of data from a csv file into a numpy array consisting of x, y, and z values, I have organized the lines by sorting them based on their x and then y values to achieve the desired order. A current issue is that this dataset comprise ...