find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link

My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center property, it always displays the middle item in my array.

I am attempting to calculate the active item by determining the middle item in my array using the following approach:

<script>
    export default {
        data() {
            return {
                slides: [
                    {
                      title: 'I am slide A',
                      featured: 1,
                      img: '/images/carousel-img.png',
                      id: 1
                    },
                    {
                      title: 'I am Slide B',
                      featured: 0,
                      img: '/images/carousel-img.png',
                      id: 2
                    },
                    {
                      title: 'I am Slide C',
                      featured: 0,
                      img: '/images/carousel-img.png',
                      id: 3
                    }
                ],
                activeImage: (this.slides.length / 2)
            };
        }
    }
</script>

Unfortunately, this method does not work as intended. I am stuck at this point and would appreciate any guidance on how to proceed in the right direction.

Thank you.

Answer №1

slides.length / 2 will provide a float value when the array has an odd number of items. To obtain an integer value, try:

Math.floor(slides.length / 2)`

or

~~(slides.length / 2)

You can then use this index to access an item in the array

slides[Math.floor(slides.length / 2)]

For example:

const demo = new Vue({
  el: '#demo',

  data: {
      slides: [
        {
          title: 'I am slide A',
          featured: 1,
          img: '/images/carousel-img.png',
          id: 1
        },
        {
          title: 'I am Slide B',
          featured: 0,
          img: '/images/carousel-img.png',
          id: 2
        },
        {
          title: 'I am Slide C',
          featured: 0,
          img: '/images/carousel-img.png',
          id: 3
        }
      ],
  },

  methods: {

    getActiveImage: function () {
        return Math.floor(this.$data.slides.length / 2);
    }

  }
});

// In template: <div> {{getActiveImage()}} </div>

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

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

What is the best way to receive the result of an asynchronous function as an input and showcase it using express?

I have recently started learning about node and express My goal is to create an API that can fetch data from an external source and use that data for my application Is there a way to retrieve the result of an asynchronous method and display it using the ...

JavaScript code to activate a text box when a checkbox is clicked

I have a dynamic table that is generated by JavaScript based on the selected item from a dropdown list. The table consists of a column for checkboxes, a column for displaying names, and a column for inputting quantities. I would like to have all textboxes ...

Accessing data attributes using jQuery and the class selector

I'm looking for a way to trigger an onClick event for an entire class of elements and access their individual data attributes within the function. Typically, I would use the following method: $(".classy").click(function(){ console.log("Replace th ...

Retrieve the <style> tag response and inject it into the head section of the HTML using React

Although I am aware that this may not be the best practice, it seems to be the most suitable solution for this particular case. The server response contains something like this: <style id="styles">.color_txt{color:green;}</style> I am attempt ...

Tips for incorporating conditions when updating data in MongoDB

I am looking for assistance with updating the secondary phone number in the code below. I want to update it only if a 10-digit number is passed from the web form; otherwise, I would like to use the already inserted phone number during the insert operation. ...

Angular Navigation alters the view

I want to navigate to a different page using Angular routing, but for some reason it's not working. Instead of moving to the designated Payment Component page, the content is staying on my Main Component. Why is this happening? app.routing.module.ts ...

What could be the reason behind the malfunctioning of $.getjson?

I've been facing issues trying to access remote json data. Initially, I resorted to using as a temporary fix but it's no longer serving the purpose for me. As of now, I am back at square one trying to resolve why I am unable to retrieve the remo ...

How can I stop VSC from automatically inserting "require"?

Every time I edit certain JS files in VSC, it automatically inserts "require()" calls that I then have to delete. Is there a way to stop VSC from adding these lines with "require"? Appreciate any help, Didier ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

A basic problem involving appending content using jQuery

I have encountered a puzzling issue. Whenever I attempt to insert new content into the <div> element using my JS code, it briefly appears and then disappears abruptly. I am unsure of the reason behind this behavior. Is there a way to prevent this fr ...

JavaScript is failing to pass the argument value

Whenever I attempt to pass a value on an onclick=function('') function, the value does not seem to get passed correctly while ($row = mysqli_fetch_array($result)) { $id = $row['id']; echo '<a href="#" onclick="DeleteUse ...

Restricting JSON output using date and time values within the JSON object

Currently, I'm in the process of creating a play data reporting tool specifically designed for a radio station. The main concept involves retrieving play history from the playout software's API and manually adding tracks that were played outside ...

This asynchronous function will provide a response of "undefined"

Having a challenge with an async function that should return a geocode value: async function getLocationCoordinates(place){ //var str; return googleMapsClient.geocode({ address: place }).asPromise() .then((response) => { response.json.results[0].ge ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...

Code snippet for converting the current webpage into a PDF using Jquery

Looking for guidance on how to convert the current webpage into a PDF using client-side (JQuery) code. The PDF should include all content from the webpage along with a few images if possible. The main requirement is to have all webpage content in the PDF, ...

What could be causing the issue of HTML Button not functioning properly with jQuery Webpack?

I'm currently using webpack to build my HTML and javascript files. I have a function defined in index.js and I've attempted the solutions mentioned here, but none of them seem to work for calling the function onclick button. Here is the HTML cod ...

Creating clickable div elements within a loop

In the .JS file I have the function below (which I later call in an HTML file): function writeDiv(){ x = 1 myArray.forEach(item => { htmlText += '<div class="divsArray">'; htmlText += '<h5> Value of X ...