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

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

What could be causing this unexpected delay?

I have been working on improving the load time of my website as it was quite lengthy, but even after optimizations, I am facing issues specifically with the jQuery UI CSS images. If you could spare a moment, would you mind taking a look at this Pingdom te ...

Best Method for Updating a Single Scope and Setting the Others to False in AngularJS

If I have 4 fields in my view that need to be toggled open or closed when clicked, with the requirement of closing the other three, how can this be achieved without duplicate code? <div class="square red"></div> <div class="square blue"> ...

innerhtml does not display the entire array contents

I'm facing an issue with my innerHTML output where it seems to be displaying one less value than expected from the array. I've been unable to pinpoint the exact problem. await fetch(urlbody, bodyrequestOptions) .then((response) => response ...

Embracing Error Handling with ES6 Promises

I am seeking clarification on how errors travel through a series of then continuations to a catch continuation. Consider the following code: Promise.reject(new Error("some error")) .then(v => v + 5) .then(v => v + 15) .catch(er ...

Obtaining the responseJSON property from a jQuery $.ajax object involves accessing the data returned

Recently, I encountered an issue with my JavaScript code that involves an AJAX request: $ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {} ...

Error loading content for webpack://SwaggerUIBundle/src/core/system.js in Swagger UI

When trying to utilize Swagger UI for documenting a Laravel project using the URL http://localhost:8014/api/documentation, I came across an error displayed in the browser console: Error: Unable to destructure property 'type' of 'u' as i ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

Acquire the item that is found in every array (Javascript)

In my data, I have multiple arrays like the following: { names: [0, 1, 2], gender: [2, 5, 1], boolean: [7, 2, 1, 6] } Is there a way to extract the value that appears in all arrays? For example, how can I retrieve the value 1 since it is prese ...

Utilize HTML5 to send a document to Google Drive API

I'm currently developing a Google Chrome extension that utilizes the Google Drive API to upload files. While handling text files isn't an issue, I encounter errors when attempting to upload binary files. When trying to upload a file using the Fi ...

In Python, carry out a Google search and specifically retrieve the content from the top 10 results

Currently, I am in the process of developing a script that will conduct a Google search based on a specified keyword and then extract only the content from the top 10 resulting URLs. Please note: By "content," I am referring to the specific information re ...

Learn how to gradually make text disappear and reappear using JavaScript or jQuery

I am a beginner in JavaScript and jQuery, and I am trying to achieve a text fade-out effect. Once the text has completely faded out, I want it to return with the same fade-in effect. I have been exploring if statements and fadeIn effects, but I am strugg ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

The poster image functionality in videos is experiencing issues after updating to version 1.5.0 of the Azure Media Player

I've encountered a strange issue after updating my azure media player to version 1.5.0 - it's not displaying the poster image like it did in version 1.3.0. Below is the code I'm currently using: <div class="marginBlock" id="mediaPlayer" ...

Error alert: $.simpleWeather function not found

Currently, I am attempting to incorporate simpleWeather.js from the website simpleweatherjs.com into my own website. However, upon inserting the html code onto my website, an error message pops up: Uncaught TypeError: $.simpleWeather is not a function ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...

Currently experimenting with jQuery in conjunction with the reddit API to generate individual divs for every post

Issue with displaying post titles, URLs, and permalinks separately. Need them to display together for each post. See the code below: $(document).ready(function() { $.getJSON( "http://www.reddit.com/r/pics.json?jsonp=?", function foo(data) { ...

Guide to dynamically modify the font family value of the entered text

I have a simple question regarding customizing font styles. I have an input text field and a drop-down list with various font family options. My goal is to display the text entered in the input field in the selected font style from the dropdown list. Can ...