What steps can be taken to swap out @click with addEventListener and enhance addEventListener to be just as versatile as @click

When using Chrome on Android, playing music or video is restricted if there are no user movements detected. I came across some code from Google that utilizes the addEventListener method to detect user interactions and enable the playback of music or video.

Interestingly, I noticed that in Chrome on Android, utilizing the @click attribute prevents tracks from playing. After much debugging and research, I discovered that while Chrome begins playing the track momentarily, it quickly stops. This behavior seems to be due to Chrome interpreting @click as an auto-play feature that might display advertisements, rather than recognizing it as a valid user interaction trigger. By switching to the use of addEventListener, Chrome successfully plays the media without any issues. While this solution works for me, there are still two challenges:

1) I need a way to pass the trackObj from the template to the event listener's function;

2) If there are hundreds of tracks, I am unsure if adding listeners to each one is feasible.

<template>
  <div v-for="(trackObj, index) in tagObj.tracks" :key="trackObj.trackId">

    // What currently functions on PC but not on Android with Chrome
    <b-card @click="nextTrack({whatToDo: 'playTrackObj', trackObj: trackObj})"
      class="dragula-move w-100 pl-2" no-body>
      {{ index + 1 }}. {{ trackObj.trackTitle }}
    </b-card>

  </div>
</template>

<script>
  import { mapActions } from 'vuex'

  export default {
   methods: {
     ...mapActions('header', [
       'nextTrack'
     ])
   },

   // Solution for Android with Chrome
   mounted () {
     // let self = this

     // let allTracks = document.getElementsByClassName('card dragula-move w-100 pl-2')
     // for (let i = 0; i < allTracks.length; i++) {
     //   allTracks[i].addEventListener('click', function (event) {
     //     self.nextTrack({whatToDo: 'playDefaultTrack'})
     //   })
     // }
   }

 }

</script>

If I remove the @click="nextTrack(...) attribute from the <b-card> element and uncomment the code in the mounted() function, Chrome on Android successfully detects user interactions and initiates track playback.

I am curious if there is a way to assist Chrome on Android in acknowledging user clicks while still utilizing my current code (i.e., @click="nextTrack(...)), or if someone can provide guidance on how to pass a trackObj from the template to an EventListener that can then be utilized by the self.nextTrack(...) function?

The use of @click.native does not resolve this issue.

Answer №1

To optimize your code, I recommend implementing a custom directive using the objects as arguments. Here is an example:

Vue.directive('custom-directive', {
  bind: function(el, binding, vnode) {
    var vm = vnode.context;
    el.addEventListener('click', function(event) {
      vm.customFunction({arg: binding.value.arg})
    })
  }
})

new Vue({
  el: '#app',
  data: {
    message: 'hello!',
    obj: 'something'
  },
  methods: {
    customFunction(arg) {
      console.log('Custom function called with', JSON.stringify(arg))
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c0c3d3f6849883988785">[email protected]</a>/dist/vue.min.js"></script>

<div id="app">
  <div v-custom-directive="{arg: 'value1', obj: obj}">
    Action 1
  </div>
  <br>
  <div v-custom-directive="{arg: 'value2', obj: obj}">
    Action 2
  </div>
</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

Increasing the number of elements in a multi-dimensional array in React

Hello everyone, I am reaching out because I am having trouble with my work schedule. I need to update each checkbox based on whether it is true or false (tasks array contains checkboxes in the front end). Data seeds const datas = [ { id: 10, ...

angular.js:13550 Error: Unable to access the 'compile' property because it is undefined

I encountered an issue with the AngularJS code below: "angular.js:13550 TypeError: Cannot read property 'compile' of undefined" for the code- HelloWorld.html <!DOCTYPE html> <html ng-app="module1"> < ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Display images from the wikipedia API using asynchronous JavaScript and XML (AJAX

I am attempting to display the images from a Wikipedia article. For example, from To work around the cross-origin policy, I am using a proxy: function imageWp() { var word = 'Appendizitis'; $.ajaxPrefilter( function (options) { if (options ...

Issue with using puppeteer for testing applications

Having an issue as a beginner in JavaScript, I'm struggling to solve this error. I am fetching data from a website using puppeteer and trying to verify if it's the correct one: const puppeteer = require('puppeteer'); (async () => { ...

Which Android applications support websocket clients?

I created a Java-based chat application prototype using Jetty client and Tomcat 8 server for websocket communication. Now, I want to port the client to Android. However, I'm encountering errors like the ones below: 12-18 23:43:59.016 2315-2315/com ...

Modify the CSS based on the number of elements present in the Meteor collection

Currently, I am in the process of developing an application that will enable users to save equations and access them from a homepage. The goal is to have a button labeled "Equation" appear on this homepage. However, I am faced with the challenge of styling ...

What could be causing my Vue.js project's favicon not to show up?

My favicon has suddenly disappeared from my Vue.js project, despite it working fine before. I haven't made any changes to the code related to the favicon or moved the file. In the <head> section of my index.html document, I have linked to the fa ...

Do developers in the tech industry typically view Hybrid Mobile apps as lesser quality compared to Native apps?

My group embarked on a college project to develop a cloud messaging app for Android. Our journey began with exploring the Ionic Framework and Phonegap to create a Hybrid app. Initially, we were drawn to Hybrid app development because it allowed us to util ...

Embedding Views in a <td> tag with DataTables and Ember.js

Has anyone ever attempted to incorporate a view within a using data tables? Currently, I am loading the data and dataTables through didInsertElement. Within each record, I am adding an "edit" and "delete" button inside a td so users can click to edit or d ...

Issue: Cannot assign type 'Promise<PostInfo>[]' to type 'PostInfo[]' while updating state

At the moment, I am facing an issue with my function that fetches an API and updates state. Specifically, I encounter an error when attempting to assign a Promise to the state. type DataState = { postList: Array<PostInfo>: }; const [state, setSt ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

Press anywhere else on the screen to dismiss the bootstrap menu

I've been attempting to find a solution for closing the Bootstrap menu when clicking outside of it in a mobile window size, but I just can't seem to make it work. I did manage to get it working when clicking one of the 'a' links using t ...

Troubleshooting issues with TypeScript D3 v4 module import functionality

As I embark on the journey of creating a miniature JS library using D3 to visualize line charts, I find myself navigating unfamiliar waters. However, I believe that deep diving into this project is the most effective way for me to learn. Below is the cont ...

What is the best way to restore the original dimensions of images after they have been altered?

I have content displayed on a webpage with images, each image having a specific width or none specified. When a user clicks a button, the content is exported to a PDF file. To ensure the images fit correctly on the PDF page, I adjust their width and height ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...

Extract the color value using the Spectrum color picker

I successfully integrated the Spectrum color picker into my project. $(document).ready(function() { $("#font_color").spectrum({ color: "#f00" }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scri ...

utilizing Javascript to display file contents within a textarea

I am trying to utilize JavaScript to display the contents of a local file in a textarea tag. After some research, I came across the following solution: <textarea id="queryContent"></textarea> <input type="file" multiple id="queryInput"& ...