Utilizing Object-Oriented Programming in JavaScript for Image presentation

I am struggling to show an image using a <button> element and it seems like there is an issue that I can't figure out.

Despite reading various resources on Javascript and OOP, I am still unsure if I have implemented the concepts correctly in my code.

Let me share with you how my code looks:

function myFunction() {
    function Image(src, height, width) {
        this.src = src;
        this.height = height;
        this.width = width;
    }
    image.prototype.display = function () {
        document.body.appendChild(image);
    }
    var image = new Image("image.jpg", "200", "200");
    image.display();
}
}

I really hope someone can assist me with this problem. Thank you! :)

Answer №1

To accomplish this task, you must first create a DOM element and then assign attributes to it. An effective demonstration of this process can be found on jsfiddle:

http://jsfiddle.net/XYZ123/

function customFunction() {

    function Picture (src, height, width) {
        this.src = src;
        this.height = height;
        this.width = width;
    }

    Picture.prototype.displayImage = function() {
        var pic = document.createElement('img');
            pic.setAttribute("src", this.src);
            pic.setAttribute("height", this.height);
            pic.setAttribute("width", this.width);
        document.body.appendChild(pic);
    }

    var picture = new Image ( "http://www.example.com/image.jpg", "300" , "300" );

    picture.displayImage();
}

customFunction();

Answer №2

Since you are creating your own Picture class, it seems like you haven't included any elements that can be displayed on the web page.

A revised version of your show function could resemble the following (pay attention to the capitalization of Picture):

Picture.prototype.show = function() {
    // It may be more appropriate to include this in the constructor
    // for example, having one image element per Picture object
    var pictureElement = document.createElement("img");
    pictureElement.src = this.source;
    pictureElement.style.height = this.height;
    pictureElement.style.width = this.width;
    // Additionally, appending the image to the body every time show is called
    // may not be ideal; using style.display = "inline" or similar
    // along with a hide method might be a better approach
    document.body.appendChild(pictureElement);
}

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

nested dropdowns in Bootstrap 4

I'm currently working on a nested dropdown menu feature. Although I have successfully implemented the functionality to display the next level, I am facing an issue where it does not close upon clicking. Check out my code here! Here is the JavaScript ...

Connect the incoming http request information to a different controller

My navigation menu has the following structure: <div class="collapse navbar-collapse" id="admin-side-nav" ng-controller="AdminNav"> <ul class="nav nav-pills nav-stacked"> <li><a href="/admin/leaderboard/{{gameId}}">Lead ...

Surprising Regex Match of ^ and special character

My regular expression is designed to break down calculator input strings, such as 12+3.4x5, into individual tokens like 12, +, 3.4, x, and 5 Here is the regular expression I am using: \d+\.?\d+|[\+-÷x] However, I am encountering une ...

The use of callbacks in Model.findById() is now deprecated due to a MongooseError

Hello there! I've run into an issue and could use some assistance, thank you in advance! Running MONGOOSE VERSION: "mongoose": "^7.0.3" Error Message: MongooseError: Model.findById() no longer accepts a callback at Function.findB ...

Using Javascript regular expressions to substitute $1 with the result of f($1)

I need to update a regular expression, let's say it looks like this: /url.com\/([A-Za-z]+)\.html/. My goal is to replace it with new string $1: f($1), which involves a constant string with two interpolations - the captured string and a funct ...

Retrieving an element based on user input's value

Having trouble comparing multiple input elements to another input by matching values. The problem arises when attempting to match values with user input on the page load, unlike when the inputs already have values. Check out the JSFIDDLE here <script ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

Developing a Prototype for an Angular Directive

After following instructions from a question on Stack Overflow, I have updated my application configuration with the code snippet below: $provide.decorator('formDirective', function($delegate) { var directive = $delegate[0]; directive.contro ...

Using Dropzone.js to bypass the Browse dialog when uploading files in integration tests with php-webdriver

Currently, I am implementing dropzone.js in my project. I have a specific requirement where I need to manually add a file to the queue without triggering the file browser dialog box. The dropzone has been initialized on the element with the class .imageDro ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...

Resizing the Canvas in Three.js with GLSL

I'm currently facing challenges with maintaining the proportions when resizing the window to smaller sizes on mobile devices as shown in this CodePen. The lines and interaction become difficult to see on mobile screens. Is there a solution to address ...

Determine all the names of imported files in a source file using regular expressions in JavaScript

Hello, I'm new to working with regex and JavaScript. I'm attempting to use regex to create an array of all imported files in a source file. In the source file, there is an '@' sign before an import statement. For example, if the file lo ...

Show a pop-up window when a button is clicked, just before the page redirects

Is there a way to display a popup message before redirecting to another page when clicking on a button? Here's the scenario: <a href="addorder.php?id=<? echo $row01['id']; ?>" ><button id="myButton" class="btn btn-primary btn ...

switching the icon for custom sorting in AngularJS

I managed to implement a custom grid style and sorting icon in AngularJS successfully, except for the toggling of the sorting icon. Here is my HTML code for headers: <div ng-app="myApp"> <div ng-controller="TableCtrl"> <table ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Synchronous execution in Node.js: Best practices for coordinating tasks

While Node.js is known for its asynchronous nature, I am seeking to perform tasks in a sequential manner as outlined below: 1. Make an API request > 2. Convert the body from XML to JSON.stringify format > 3. Pass the string to a template. request.g ...

Using AngularJS to retrieve DOM elements within a directive's controller

Currently, I am in the process of creating a custom image carousel directive using only AngularJS and no additional libraries. simpleCarousel.$inject = []; function simpleCarousel() { var directive = { restrict: 'E', templat ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...