add function to the div element

I have encountered a peculiar task. My goal is to add an additional functionality to an element when it is clicked. However, I am unable to activate the addScroll function located within my methods. The intended behavior is for the div to be appended to the screen upon clicking the button. Furthermore, after clicking on the appended div, the remove method should be triggered along with the desired addition of addScrollBack().

new Vue({
  el: "#app",
  data: {
    chocs: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {
  addScrollBack: function(){
  alert("test");
  },
handlePosterClick: function(choc){
alert("clicked")

     window.top.$(".2l-body").css("overflow","hidden");
    
$("#cook").append(`<div style="background-color:blue;height:200px; width:300px" onclick="document.querySelector('#popover-div').remove();addScrollBack();">test</div>`);
   
   },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="cook">

  </div>
  <button v-on:click="handlePosterClick(choc)">
        Book
        </button>
</div>

Answer №1

Check out this link:

https://codepen.io/hl037/pen/QWOjwyK

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  
  {{displayDiv}}
  <div id="cook">
    <div
      v-if="displayDiv"
      style="background-color:blue;height:200px; width:300px"
      v-on:click="onDivClicked"
    >
      test
    </div>
  </div>
  <button v-on:click="displayDiv=true">
    Book
  </button>
</div>
new Vue({
  el: "#app",
  data: {
    displayDiv:false,
    chocs: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true },
    ],
  },
  methods: {
    onDivClicked(){
      /*document.querySelector('#popoverdiv').remove();*/
      this.addScrollBack();
    },
    addScrollBack: function(){
      alert("test");
    },
    handlePosterClick: function(choc){
    },
  }
})

Instead of manually changing the DOM, it's better to utilize Vue's template with a controlling model for behavior. The same goes for other components like the popup - they should listen for custom events on this component for scroll functionality using reactivity.

Avoid using vanilla JavaScript for DOM manipulation or event handling when working with Vue. Always follow Vue's recommended way of doing things. Direct DOM modifications should be left to experts, especially when integrating with non-Vue code.

Answer №2

It's a bit unclear, but my suggestion is to utilize v-html instead of using append

new Vue({
  el: "#app",
  data: {
    cook: "Old content OR blank",
    chocs: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  methods: {
  addScrollBack: function(){
  alert("test");
  },
handlePosterClick: function(choc){

//alert("ckciked " + choc)
// window.top.$(".2l-body").css("overflow","hidden");


// inline Scripting not recommanded,
 this.cook= `<div style="background-color:blue;height:200px; width:300px" >test</div>`;
   
   },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div id="cook" v-html="cook">
    
  </div>
  <button v-on:click="handlePosterClick('choc')">
        Book
        </button>
</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

Async/Await Jumping the Gun Without Waiting for Promise to Resolve

My understanding of using await seems to be incorrect. I believed that by using an async function and the await keyword on a promise-returning call (like navigator.mediaDevices.getUserMedia), the function execution would pause until the promise is resolve ...

What is the best way to utilize an "as" property in TypeScript when forwarding props to a component?

I am currently working on creating a collection of components, and I require some of them to have the option of a customizable tag name. For instance, there are times when what seems like a <button> is actually an <a>. Therefore, I would like t ...

Is there a Javascript database that functions seamlessly on Android, IOS, and Windows Phone 8 (Internet Explorer 10)?

I am currently maintaining an app for Android, iPhone, and Windows that relies on an ASP.NET Server with SQL Server Database. I would like to make the app functional offline as well, which requires utilizing a database on the client side. Despite my best ...

When using tinymce, remember to paste the HTML tag <poll poll-id="'POLL ID'"> in

Every time I attempt to paste in the code editor, it cuts off my tag. The editor simply won't allow it... I'm at a loss, I've exhausted all options. Is there anyone who can assist me? <div class="polls form" id="poll-container" ng-app=" ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Mastering CSS States: Hover and Active

Imagine we have a link with the class "myClass1". Using JavaScript, we are able to manipulate the classes for this link - for instance, adding "myClass2" to it. My query is whether we can also manage states through JavaScript, such as removing the hover s ...

Struggling to create the passingGrades function in Javascript, which aims to eliminate any grades below 70 from an array but unfortunately encountering issues

There seems to be an issue with the code snippet provided below. I'm having trouble identifying the problem and would appreciate any assistance. var scores = []; var passingScores = function(scores) { for (i=0; i < scores.length; i++){ co ...

Encountering a Babel error while working with ReactJs

I am facing a new error message while trying to launch my ReactJs project. The project worked fine previously, and I'm unsure why this sudden issue has appeared: module.js:338 throw err; ^ Error: Cannot find module 'tapable' at ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

Retrieve the ID of the clicked list item

Below is a list that I have: <ol class="sortable ui-sortable"> <li id="list_1608"><div>One</div></li> <li id="list_1609"><div>Two</div></li> <li id="list_1610"><div>Three</di ...

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

Illuminate objects using three.js

My expertise in shaders and three.js is limited, however I am currently experimenting with creating a dynamic glowing effect similar to lights being flicked on and off. Currently, I am adjusting the color saturation and lightness which somewhat achieves ...

Attempting to stop an Ajax form from sending in its usual manner will not prove successful

I am currently working on implementing a form submission using Ajax. I have tried using event.preventDefault(); to prevent the form from submitting normally, but I am still being redirected to my sendMail.php file. Below is the code I am using: $(documen ...

Using jQuery to select all child elements based on a specified condition

Is there a way to locate all instances of .post-comment-replies that have a nested '.post-comment-reply' within them, rather than being at the first level? Currently, the code provided retrieves not only those .post-comment-replies with nested . ...

Issue encountered while running Java scripts in Selenium with JMeter due to method invocation error

When attempting to run JavaScript in my Selenium code, I encountered the following error: Error: Response message: javax.script.ScriptException: Sourced file: inline evaluation of: import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; impo ...

An easy way to select multiple checkboxes from an array using Angular 6

When editing data, I have a form that includes checkboxes. I need to ensure that the previously selected checkboxes are checked in the edit profile form based on the array retrieved from the database. Code snippet from app.component.html: <form [formG ...

When establishing a many-to-many relationship in Mongoose, the use of populate() may not be suitable

I am facing an issue while trying to establish a many-to-many relationship using mongoose for employee creation. When I call the .post method, I encounter the following error: TypeError: Employee.create(...).populate is not a function Interestingly, my . ...

Exploring Grunt (node): Ways to Display Available Tasks

While I am accustomed to using Rakefile, Cakefile, and Jakefile, each of them offered a convenient method for listing the tasks available. For example: jake -T jake db:dump # Dump the database jake db:load # Populate the database ...and so ...

Trouble locating the elusive element with Selenium

Currently, I am working on creating a framework that involves determining whether a web element is hidden before executing any actions on it. One specific scenario involves a password field that is structured like so: <div class=hidepassword> < ...