Display an image in a DIV by loading it from a URL provided in a TEXT BOX

I am having trouble loading an image into a div tag from a URL that is obtained from a text box. Here is my current code snippet, but I can't figure out what else needs to be done:

<html lang="en">
    <head>
    </head>
    <body>
        <input type="text" class="imageURL1">
        <div class="ImageContainer">
          The image will display here:  
        </div>
    </body>
</html>

Answer №1

If you want to use pure JavaScript to dynamically load an image, you can achieve it by utilizing the onChange event to check if a URL has been entered into the text box. When the Enter key is pressed, the image will be loaded into the designated div element.

function addImage()
{
  var url = document.getElementsByClassName("imageURL1")[0].value;
  var image = new Image();
  image.src = url;
  document.getElementsByClassName("ImageContainer")[0].appendChild(image);
}
<html lang="en">
  <head>
  </head>
  <body>
    <input type="text" class="imageURL1" onChange="addImage();">
    <div class="ImageContainer">
      The image will display here:  
    </div>
  </body>
</html>

Answer №2

You might want to give this a try.

$(document).ready(function(){
    $("#Submit").click(function(){
        var image_url = $(".imageURL1").val();
        $(".ImageContainer").html("<img src='"+image_url+"' width='200'>");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="imageURL1">
<button id="Submit">Submit</button>
<div class="ImageContainer">
          
</div>

View an example on Js Fiddle -> http://jsfiddle.net/0kvxpnmv/

Answer №4

Utilize php

index.php file
<form action="GetURL.php" method="post">
<input type="text" name="url">
<input type="submit">
</form>

Upon clicking submit, you will be directed to a new page

GetURL.php

$image_url = $_REQUEST['url'];

<html lang="en">
    <head>
    </head>
    <body>
        <input type="text" class="imageURL1">
        <div class="ImageContainer">
          <?php echo '<img src="{$image}"/>'; ?>
        </div>
    </body>
</html>

The code here shows that within the imageContainer class, the image URL is being displayed using PHP

To enhance this feature, consider having the form and image on the same page and utilizing Ajax to post the URL.

You can enter the desired URL in the textbox and upon completion, the image URL will refresh.

Answer №5

How about implementing a button to execute a function that replaces the image source with the URL provided in the text box

HTML

<html lang="en">
    <head>
    </head>
    <body>
        <input type="text" class="imageURL1">
        <button onclick="func()">Load image</button>
        <div class="ImageContainer">
          <img src="" id="imgContainer">
        </div>
    </body>
</html>

javascript

(function(){
var func = function(){
 var url = $(".imageURL1").val()
 $('#imgContainer').attr('src',url)
}

})();

Check out the jsFiddle with jQuery and without jQuery

Answer №6

To display an image based on the URL entered in a text input field, I have provided code below. Whenever there is a change event on the ".imageURL1" element, a jQuery img tag will be created using the URL from the input as the source. The content of the output div will then be cleared before displaying the loaded image.

$('.imageURL1').change(function() {
    var $img = $('<img/>');
    $img.attr('src', $(this).val());
    $img.load(function() {
        $('.ImageContainer').html(this);
    });
});

Please note that this solution makes use of jQuery library.

You can see a live demo by visiting this link.

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

The issue arises when a continuous use of angularjs directives linked with an external template fails to display correctly upon the addition of new

In the code snippet below, you'll find a fiddle that displays 3 columns of numbers that increase in value. These columns represent directives with different templates: one inline, one preloaded, and one from an external template. When you click on the ...

I am experiencing an issue with the HTML5 video tag as it is not displaying the

Having trouble playing a user-uploaded video using the <video tag. The video doesn't seem to load into the DOM properly. Here's the code snippet: function Videos ({uploadedFiles}){ if (uploadedFiles) { console.log(uploadedFile ...

UI thread was blocked due to withProgress being invoked from an external library function

Currently enhancing an extension that is almost finished, but facing a challenge in adding visual cues for lengthy operations. Initially suspected a missing async/await in the code, but struggling to identify the cause. The progress indicator isn't di ...

Is it more beneficial to keep a function inside or outside another function if it is only being used within it?

Within the topic at hand, I have a function structured as follows. There are numerous auxiliary functions declared within this function (twice the amount shown in the example) because they are solely utilized by this function. My query is: should I extrac ...

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Styling an HTML Table with CSS to Add Cell Padding

I am trying to add padding to a single cell in my table. I created a class for the td element and specified its style in my CSS file as shown below: .itemQuantity { padding-right:30px; text-align:right; background-color: #EEE; } However, the ...

Selecting an option on JQuery UI Autocomplete replaces the displayed label with its corresponding value

Currently, I am utilizing JQuery UI Autocomplete along with an ASP.NET Textbox to display both the label and the value. The following snippet showcases how I have mapped the data fetched from an ajax call: success: function (data) { response($.map(dat ...

What is the method for utilizing a parameter in a protractor configuration file to select specific steps?

After reading this particular question, I attempted to implement the following: protractor test/features/protractor-conf.js --params.test_set=dev_test as well as protractor-conf.js: exports.config = { // ... specs: [browser.params.test_set+'/ ...

Passing onClick event to parent component during iteration in ReactJS

I am facing a challenge where I need to remove a row from a table upon a click event. I have managed to create an iteration and display a delete button, but I am struggling with passing the onClick event from the parent component to the child component in ...

Ways to utilize CSS for capturing user-inputted text in a text field

I have a question about incorporating user input text into CSS styling. Specifically, I am looking to create a color background option (#ffffff) where the designer can input their own color and have it displayed once saved in the body background style. Wh ...

How does the Angular2-all.umd.js compare to the angular2.js file?

Currently, Angular 2 is in its 13th beta phase. I came across https://code.angularjs.org/2.0.0-beta.13/ and noticed that there are two different versions of Angular2 available: angular2-all.umd.js angular2.js What distinguishes these two versions from ...

"Troubleshooting: Child Component Not Reflecting Changes in UI Despite Using Angular

My child component is designed to display a table based on a list provided through @Input(). The data is fetched via http, but the UI (child component) does not update unless I hover over the screen. I've seen suggestions about implementing ngOnChange ...

Guide on implementing hover effects in React components

Within my component SecondTest, I have defined an object called useStyle which sets the background color to red. Is it feasible to add a hover effect to this object? const useStyle = { backgroundColor: "red", }; function SecondTest() { return < ...

What is the method to retrieve data in Vue when utilizing arrow functions?

When utilizing Vue and arrow functions in methods, we encounter the issue that arrow functions do not have a this keyword. The question then arises of how to access data properties such as list or object. export default { data() { return { list ...

Click on a row to be redirected to a webpage with a dynamic parameter included in the URL

In my Jade template, I have a row that looks like this: tr(data-href="http://localhost:3000/patient/" + patients[0].patient[g]["number"]).clickable-row. When rendered in the HTML console, it outputs as: <tr class="clickable-row" data-href="http://local ...

Exploring the dynamic subpaths in Next Js

As I progress with my next.js app, everything has been running smoothly until my client requested a challenging feature for me to tackle. The site currently resides at mysite.com with routes like mysite.com/cars, mysite.com/vehicles, etc. Now the client ...

What is the secret to remaining on the same spot even after the page is reloaded?

How can I maintain the AJAX call data after a page reload? I have attempted to use code that reloads the entire page, but I would like to stay in the same location. Is there a way to achieve this without reloading the entire page? $('#updateAddressPr ...

A guide on tapping into the creation event of an express session

Is there a way to determine when express creates a new session? Specifically, I am utilizing a mongodb session store. I have been encountering an problem related to multiple sessions being generated and I would like to identify the root cause by monitorin ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

What is the best way to locate an element with the class name being an email address using jQuery?

Is it possible to locate an element with an email address as the class name, considering that the email address varies? $(document).ready(function(){ //not working getting error var email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...