Automatically refreshing the canvas whenever the value of an HTML element is modified in Javascript

Below is the javascript code that is relevant

<script>
    $.fn.ready(function() {
        var source = $('#source').val();
        Meme('url1', 'canvas','','');
        $('#top-line, #bottom-line').keyup(function() {
            Meme(source, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            if(document.getElementById('stanley').checked) {
                source = 'url2';
                Meme(source, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            } else if(document.getElementById('futurama').checked) {
                source = 'url3';
                Meme(source, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            }
        });
    });
</script>

Here is the HTML content

<div class="col-lg-12 col-md-12 col-sm-12">
    <input type="radio" name="meme" id="stanley" class="input-hidden" />
    <label for="stanley"><img src="url3" alt="" width="80px;" height="80px;"/></label>
    <input type="radio" name="meme" id="futurama" class="input-hidden" />
    <label for="futurama"><img src="url4" alt="" width="80px;" height="80px;" /></label>
</div>
<div class="col-lg-6 col-md-6 col-sm-12" id="containcanvas" style="margin-top:10px;">
    <canvas id="canvas"></canvas>
</div>
<div class="col-lg-6 col-md-6 col-sm-12" style="margin-top:10px;">
    <form>
        <input class="form-control" id="source" placeholder="Image URL">
        <input class="form-control" id="top-line" placeholder="Enter top line text">
        <input class="form-control" id="bottom-line" placeholder="Enter bottom line text">
    </form>

The canvas currently updates when the top-line and bottom-line values change. To update the canvas once a radio button is checked, the functionality has been integrated into the section where changes in the top and bottom lines affect the canvas. However, this approach is not optimal as indicated by the user. Additionally, the canvas does not update after entering an image URL in the source input field. Suggestions are needed on how to modify the code so that all canvases are updated immediately upon checking a radio button or changing any input text value.

Answer №1

The concept of callback code is straightforward and not mystical. It involves a Javascript function that is passed as an argument to another function. This allows you to store the callback function in a variable and use it for various events.

<script>
    $.fn.ready(function() {
        var src = $('#src').val();
        Meme('url1', 'canvas','','');

        var callbackFn = function() {
            Meme(src, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            if(document.getElementById('stanley').checked) {
                src = 'url2';
                Meme(src, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            } else if(document.getElementById('futurama').checked) {
                src = 'url3';
                Meme(src, 'canvas', $('#top-line').val(), $('#bottom-line').val());
            }
        });

        $('#top-line, #bottom-line').keyup(callbackFn);
        $('input[name="meme"]').change(callbackFn);
        $('#src').change(callbackFn);
    });
</script>

Consider using keyup instead of $('#src').change for better functionality, but clarity of intent is crucial.

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

AngularJS HTTP POST request encountering issue with success function not functioning as expected

I am currently working on implementing a basic HTTP post request to insert data into my database. The following pages are involved: register.php contains the registration form. maincons.js houses the application controllers. sqlregister.php include ...

Nested Async await within a timer is failing to provide the expected result

Currently, I am working on testing the responses of endpoints using Mocha and Chai tests. Below you can find the code snippet for the same: async function fetchUserData (userId) { let response; let interval = setInterval(async () => { ...

When using `require('backbone')`, the returned object can vary depending on the file it is called in

backbone1.js var backbone1=require('backbone'); window.backbone=backbone1; backbone2.js console.log(window.backbone===require('backbone')); Why is the condition returning false. Shouldn't it return the same object everytime? E ...

CSS not being applied to certain HTML elements due to an error in implementation

Utilizing Bootstrap's vue form-group has been instrumental in my creation of input fields. I am currently attempting to apply specific CSS styling to the 'legend' element within the following code: <fieldset id="__BVID__59" class="form-g ...

Adjust the size of a textarea once text is removed

When you type text, a textarea expands in size. But what if you want it to dynamically decrease its height when deleting text? $('textarea').on('input', function() { var scrollHeight = parseInt($(this).prop('scrollHeight&apos ...

How can we consolidate an excess of menu items into a condensed, collapsed menu?

I have a navigation bar displaying category items, but if the menu items exceed the navbar width, how can I condense them into a drop-down menu using Bootstrap 3.0? Currently, my navbar only shows 10 items due to limited space. However, I have more items ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

Dynamic height of a fixed-positioned Div

I encountered an issue with a Fixed positioned DIV that has dynamically appended content using jQuery. Once the height of the DIV exceeds the screen size, I am unable to view the contents at the bottom of the DIV without zooming in using the browser' ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Changing the class of an element using CSS when hovering over another

Is it possible to dynamically change the style of another element when hovering over a specific element? For example, I want a menu item to change its appearance when hovering over a submenu item. Here is the CSS code I have: ul.menu .menulink { padding ...

Customizing Image Layout with jQuery Masonry - Tips for Aligning Images

I've successfully created a jQuery masonry layout that showcases recent posts from various categories on the homepage. However, I'm facing two challenges and seeking help to address them: How do I remove the small white gaps beneath some ima ...

Overflow-y SweetAlert Icon

Struggling with a website modification issue where using Swal.fire(...) causes an overflow problem affecting the icon rendering. How can this be fixed? Here is the custom CSS code in question: * { margin: 0px; padding: 0px; font-family: &ap ...

The values returned by a NodeJS script in the Python shell are identical to those returned by Node

The following program was developed to address an issue in another application. In this program, a Python script is called from Node.js to perform a task. The Python script returns results that are then used in Node.js. NodeJS : var pythonShell = require ...

Can you explain the distinction between JSON syntax and object assignment in programming?

While exploring the Twitter Client example on Knockoutjs, one may notice that some properties are included in the JSON object while others are assigned outside of it. What distinguishes these two approaches? And why can't methods such as findSavedList ...

What is the best way to display jQuery/AJAX response in a table cell?

I am struggling with a script that retrieves data from a SQL database query and need help placing the result in a specific table cell. Here is the query: <script type="text/javascript"> $(document).ready(function(){ $('.typeval').change(f ...

What is the process for converting a file to base64 encoding, and then uploading it as a multipart file to a backend API using JavaScript

I am working on a project to create a micro-service that can receive base64 encoded data. However, when attempting to send more than 6 MB of data, I encountered the following error message: The multi-part request contains parameterized data (excluding ...

How to efficiently upload multiple files in an array using jQuery and AJAX technology

Looking for a way to upload each file separately with HTML? <input type="file" name="[]" multiple /> Struggling to figure out how to achieve this? Here is an example: $('input:file').on('change', function(){ allFiles = $(th ...

When setting the Content-Type of an S3 object to 'image/jpeg' in NodeJS, it may appear as 'application/octet' in the S3 console

I am facing an issue with the Content-Type of an image stored in my JPEG buffer. While it uploads and downloads successfully from S3, I encounter errors when trying to send it via the Messenger API programmatically. The S3 console indicates that the actual ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...