How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic.

Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked?

I have successfully implemented this in a basic JavaScript game, but I'm having trouble integrating it into Ionic. Since it's within a tab screen, do I need to write the JavaScript differently?

The code below includes jQuery, which may not be easily supported by Ionic.

If someone can assist me, all I need is a way to store a variable (likely using localforage), display the variable (using a span element), and increase the value of the variable when a button is tapped or clicked.

Thank you so much! I've been struggling with this for two days now and still no luck...

It's challenging to provide all my Ionic code as it spans across more than just three files...

var coffee = localStorage.getItem("coffee") ? localStorage.getItem("coffee") : 0.0;
var totalCoffee = localStorage.getItem("totalCoffee") ? localStorage.getItem("totalCoffee") : 0.0;


var cookRate = localStorage.getItem("cookRate") ? localStorage.getItem("cookRate") : 1.0;


function prettify(input){
    var output = Math.round(input * 1000000)/1000000;
return output;
}

$("#coffeeButton").click(function(e) {

    var obj = $("#clone").clone(); 
    var img = $("#myImg").clone(); 

    $("body").append(obj);
    $("body").append(img);

    obj.html("+"+ cookRate);
    coffee += cookRate;
    totalCoffee += cookRate;
    document.getElementById("coffee").innerHTML = prettify(coffee);
    document.getElementById("totalCoffee").innerHTML = prettify(totalCoffee);

    obj.css('position','absolute'); 
    obj.css('z-index', '2');
    img.css('position','absolute');
    img.show();

    obj.offset({left: e.pageX-10, top: e.pageY-80});
    img.offset({left: e.pageX-10, top: e.pageY-50});

    obj.animate({"top": "-=80px"}, 1000, "linear", function() {
        $(this).remove();
    }); 
    img.animate({"top": "-=80px"}, 1000, "linear", function() {
        $(this).remove();
    });

});
#coffeeButton{
cursor: pointer; cursor: hand; background: #5EFF8F; border-radius: 7px; margin: 5px; padding: 20px; font: bold 30px Tahoma; text-align: left;
-webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -user-select: none;
}

#clone{
font-size: 1.5em;
font-weight: bold;
color: white;
-webkit-touch-callout: none;
-webkit-user-select: none; 
-moz-user-select: none; 
-ms-user-select: none; 
-user-select: none;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img title = "" id="myImg" src="images/cup.png" style="display:none" width="20" height="30">
    <div id="clone"></div>
<div id = "coffeeButton">Make Coffee <br /><span id = "cookRate">1</span> Per Click</div>
Coffee = <span id = "coffee">0.0</span>

Answer №1

For optimal functionality, ensure that jQuery is loaded before angular.js. Additionally, update all instances of $('#coffeeButton') to angular.element('#coffeeButton'). This modification replaces the $ symbol with angular.element when working with angular.js. More information can be found at this link.

To properly include jQuery in your project, place

<script src="jquery.js"></script>
above
<script type="text/javascript" src="js/app.js"></script>
in your HTML file.

var coffee = localStorage.getItem("coffee") ?  localStorage.getItem("coffee") : 0.0;
var totalCoffee = localStorage.getItem("totalCoffee") ? localStorage.getItem("totalCoffee") : 0.0;


var cookRate = localStorage.getItem("cookRate") ?  localStorage.getItem("cookRate") : 1.0;


function prettify(input){
    var output = Math.round(input * 1000000)/1000000;
    return output;
}

angular.element('#coffeeButton').click(function(e) {

    var obj = angular.element('#clone').clone(); 
    var img = angular.element('#myImg').clone(); 

    angular.element('body').append(obj);
    angular.element('body').append(img);

    obj.html("+"+ cookRate);
    coffee += cookRate;
    totalCoffee += cookRate;
    document.getElementById("coffee").innerHTML = prettify(coffee);
    document.getElementById("totalCoffee").innerHTML = prettify(totalCoffee);

    obj.css('position','absolute'); 
    obj.css('z-index', '2');
    img.css('position','absolute');
    img.show();

    obj.offset({left: e.pageX-10, top: e.pageY-80});
    img.offset({left: e.pageX-10, top: e.pageY-50});

    obj.animate({"top": "-=80px"}, 1000, "linear", function() {
        angular.element(this).remove();
    }); 
    img.animate({"top": "-=80px"}, 1000, "linear", function() {
        angular.element(this).remove();
    });

});

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

Removing leading zeros from numeric strings in JSON data

I am facing an issue with my jQuery-based JavaScript code that is making an Ajax call to a PHP function. updatemarkers.xhr = $.post( ih.url("/AjaxSearch/map_markers/"), params).done( function(json) { <stuff> } The PHP function returns the follo ...

Use multer-ftp to change the name of a file

I've been working on uploading a file to an FTP server using multer-ftp. The file is successfully uploaded, but I need to change the name of the file. Is there a way to accomplish this? var upload = multer({ storage: new FTPStorage({ basepath: ...

How can I compare the current page URL with the navigation bar?

Looking to compare the URL of a current page to an element in the navigation bar using jQuery. Started by assigning the current URL to a variable: var currentPage = window.location.href; Then utilized an .each function to loop through each item in the n ...

Exploring the differences between utilizing Node JS Express for server-side development and displaying console output to

Recently, I started delving into the world of node js and came across IBM's speech to text sample application (https://github.com/watson-developer-cloud/speech-to-text-nodejs). This app utilizes the express framework and showcases transcribed audio fr ...

Adjust the Navbar to be Aligned Completely to the Left and Divide it into 12

I need my navbar to be split into 12 sections so that each item occupies one section, starting from the far left of the screen. The current alignment doesn't meet this requirement as shown in the image below; Despite trying with container-fluid and n ...

Using three.js inside Colab

Here are some examples showcasing bi-directional communications between Python and JavaScript in Google Colab: I'm trying to get this simple three.js demo to work in Colab. Any tips? Despite the seemingly straightforward source code, I'm facing ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

Using AngularJS to chain promises

After coming across some advice on AngularJS validation and promises, I am interested in creating a chain of confirmation dialogs to validate multiple steps at once. By making an API call based on user input, we can determine what steps require confirmati ...

I developed a digital Magic 8 Ball program, but unfortunately, it's only providing me with one response

I'm currently working on a Discord Bot for my friends and myself. One of the scripts I've created is an 8Ball script, but it's only giving me one answer. Here's the code snippet for my variable: var rand = ['Yes', 'No&apo ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

Generating unique triangle patterns through Webgl

Recently, I began learning webgl and have been attempting to create triangles with random sizes and positions similar to the image below using javascript. I understand that I need to utilize a for loop within the function initScene() but I'm uncertai ...

Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective. arr = [ { id:1 , name:'a', title: 'qmummbw' }, { id:2 , name:'b', title: 'sdmus' }, { id:2 , name:'', title: 'dvfv' }, ...

Is it possible to extract information from a website if the body or row does not contain any attributes?

As a beginner in the world of coding and this website, I kindly ask for some patience with me. I have successfully created code to scrape a particular website, extract data, and store it in a MySQL database. Everything is working smoothly. Now, my goal i ...

Trimming Text with JQuery

My goal was to truncate a string and add an ellipsis at the end using jQuery, but my code doesn't seem to be working as intended. Below is the jQuery code I wrote: $(".link-content > h4").each(function(){ var len = $(this).text().length; ...

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

How can I send a jQuery ajax request with multiple custom headers?

I am facing an issue with my basic ajax request as I am trying to include a custom header using the following code: _auth=1,[my_apikey], Interestingly, when I make the same request using Postman, I receive a valid JSON response. However, when I attempt t ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Experiment with erroneous scenarios using React, Jest, and React-Testing-Library

I've encountered an issue with a React component that triggers an Error when there is faulty programming. Specifically, the Component requires a prop called data, and I have the following code snippet in place to check for its existence: if (!data) { ...

Installing a specific version of yarn on Ubuntu

Is there a way to install yarn version 0.27.5 in Ubuntu despite the fact that the latest update is for version 1.2.1? ...