JavaScript: Extracting filename from an URL - Does JavaScript continue its operation in the background?

Currently, I have an image upload form that provides the option to either select a file or paste a URL.
After selecting one of these options, the image is previewed and the filename is displayed below.

However, there seems to be an issue when pasting a URL. Upon inspecting the HTML, it appears that the element containing the filename keeps flashing purple, indicating continuous updates through JavaScript.
Is this behavior normal? It seems unusual to me. Can anyone clarify if this is expected or if there might be an error in my implementation?

You can try pasting an image URL like this: https://i.sstatic.net/C3zHJ.jpg

Update: To illustrate further, here is a demo: https://i.sstatic.net/a0ydd.png

jQuery(function($) {
  $('input[type="file"]').change(function() {
    if ($(this).val()) {
    error = false;
    
      var filename = $(this).val();
      filename = filename.replace(/.*[\/\\]/, '');

$(this).closest('.file-upload').find('.file_name').html(filename);

      if (error) {
        parent.addClass('error').prepend.after(
        '<div class="alert alert-error">' + error + '</div>');
  }}});
});
      

var imageLoader = document.getElementById('myfile');
    imageLoader.addEventListener('change', handleImage, false);

function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
    $('#cancel').show();
    $('#click_or').hide();
        $('input:file').attr('disabled', true);
        $('#uploader').addClass('disabled_');
        $('#bg_img').addClass('disabled_');
        $('#bg_img').attr('src', event.target.result);
        $('.file_name').show();
        $('#url').hide();
        $('#image_file').show();
        $('#crop_file').show();
    }
    reader.readAsDataURL(e.target.files[0]);}
    
    $('#cancel').click(function(e){
        $('#myfile').val("");
        $('#click_or').show();
        $('#cancel').hide();
        $('input:file').removeAttr('disabled');
        $('#uploader').removeClass('disabled_');
        $('#bg_img').removeClass('disabled_');
        $('#bg_img').attr('src', "https://i.imgur.com/j0KblIu.png");
        $('.file_name').hide();
        $('#url').show();
        $('#image_file').hide();
        $('#crop_file').hide();
    });
    
    
    var myInput = document.getElementById("url");
    
    setInterval(function(){
    if (myInput && myInput.value){
    $('#cancel_url').show();
        $('#image_url').show();
        $('#crop_url').show();
        $('#bg_img').attr('src', myInput.value);
        $('input:file').attr('disabled', true);
        $('#uploader').addClass('disabled_');
        $('#bg_img').addClass('disabled_');
        $('#url').hide();
        $('#click_or').hide();
        
        var url_filename = myInput.value;
      url_filename = url_filename.replace(/.*[\/\\]/, '');
        
        $('.file_name').html(url_filename);
        $('.file_name').show();
        }
    },0);
    
    $('#cancel_url').click(function(e){
    $('#url').val("");
        $('#bg_img').attr('src', "https://i.imgur.com/j0KblIu.png");
        $('input:file').removeAttr('disabled');
        $('#uploader').removeClass('disabled_');
        $('#bg_img').removeClass('disabled_');
        $('#url').show();
        $('#cancel_url').hide();
        $('#image_url').hide();
        $('#crop_url').hide();
        $('.file_name').hide();
        $('#click_or').show();
    });
    

var dropbox;
dropbox = document.getElementById("uploader");
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);

function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}
function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}
function drop(e) {
  e.stopPropagation();
  e.preventDefault();
  //you can check e's properties
  //console.log(e);
  var dt = e.dataTransfer;
  var files = dt.files;
  
  //this code line fires your 'handleImage' function (imageLoader change event)
  imageLoader.files = files;
}
#uploader {
  position: relative;
  width: 250px; 
  height: 250px;
  line-height: 250px;
  background: transparent; 
  border: 2px dashed #e8e8e8;
  cursor: pointer;
  color: #777;
  font-family: 'Arial';
  font-weight: bold;
  text-align: center;
  text-shadow: 0 0 10px white;
  -webkit-transition: text-shadow 0.1s linear;
    -moz-transition: text-shadow 0.1s linear;
    -ms-transition: text-shadow 0.1s linear;
    -o-transition: text-shadow 0.1s linear;
    transition: text-shadow 0.1s linear;
  overflow-x: hidden; 
  overflow-y: hidden; 
  opacity: 1;
}
#uploader:hover {
  color: #999;}
#myfile {display: none;}
#click_or {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}
#bg_img {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    z-index: -1;
    background-color: #eee;
}
#uploader.disabled_ {
  cursor: default;
}
img.disabled_ {
  object-fit:contain;
  image-rendering: pixelated;
}
#cancel, #cancel_url 
  {display: none;}

.file_name {
  font-family: 'Arial';
  font-weight: bold;
  font-size: 13px;
  color:#555;
}

button[type='submit'] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-upload">

<div id="uploader" onclick="$('#myfile').click()">
    <span id = 'click_or'>Click or drag and drop<br>to select an image</span>
    <img id="bg_img" src="https://i.imgur.com/j0KblIu.png">
</div>

<input type="file" name="myfile" id="myfile" accept="image/*">
<span class="file_name"></span>
<button type="button" id="cancel">Cancel</button>
<input type="text" name="url" id="url" placeholder=" ... or paste URL to image" autocomplete="off" class="clearable">
<button type="button" id="cancel_url">Cancel</button>
<br>

<button type="submit" name='image_file' id="image_file">Upload</button>
<button type="submit" name='crop_file' id="crop_file">Crop</button>

<button type="submit" name='image_url' id="image_url">Upload</button>
<button type="submit" name='crop_url' id="crop_url">Crop</button>

<span class="url_name"></span>

</div>

Answer №1

The following piece of code demonstrates a function that runs at intervals:

   setInterval(function(){
    if (myInput && myInput.value){
            $('#cancel_url').show();
        $('#image_url').show();
        $('#crop_url').show();
        $('#bg_img').attr('src', myInput.value);
        $('input:file').attr('disabled', true);
        $('#uploader').addClass('disabled_');
        $('#bg_img').addClass('disabled_');
        $('#url').hide();
        $('#click_or').hide();

        var url_filename = myInput.value;
        url_filename = url_filename.replace(/.*[\/\\]/, '');

        $('.file_name').html(url_filename);
        $('.file_name').show();
        }
    },0);

This piece of code represents a running function call that operates continuously.

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

Incorporate an Event into a Vue.js JavaScript string within an HTML file

I am attempting to trigger the event in a JavaScript string. Within the buffer, I have called this event: @click.prevent = "Buy($event)" However, the browser is not interpreting it correctly: https://i.sstatic.net/uHs8W.jpg Here is the code snippet: ...

Using ThreeJS to Load a Texture from an ArrayBuffer in JavaScript

If I have a JavaScript ArrayBuffer containing binary image data along with the image extension (such as jpg, png, etc), I want to create a ThreeJS Texture without the need for an HTTP request or file load as I already have the binary information. For exam ...

Can the input value in React be altered even if the state remains the same?

Why does the controlled input revert back to the state value even when the state hasn't been updated and no update cycle has been triggered, if every UI update should occur only when there are changes in "state" or "props" for a component? ...

Display different data in an HTML table for each individual click on the "Read more" event

I am currently extracting data from a SQL table to exhibit it in an HTML table. The issue I am facing is that I would like to implement a "Read More" feature to prevent clutter in the table. As I am retrieving the data row by row, I am utilizing a class n ...

Unpacking and reassigning variables in Vue.js 3 using TypeScript

I am working with a component that has input parameters, and I am experimenting with using destructuring assignment on the properties object to reassign variables with different names: <script setup lang="ts"> const { modelValue: isSelected ...

Issues are being faced with the execution of JavaScript on Heroku when using Rails 3.1

After upgrading a Rails 3.0 app to 3.1 on Heroku running on the cedar stack, everything seemed fine except for one major issue - the app's JavaScript wouldn't run. Despite the application.js file being compiled and accessible at myapp.com/assets/ ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Navigating with Angular and Express

Currently, my Angular project is configured with Express serving my index.html file. As the project progressed, I found the need for a landing page that requires some functionality from the index.html file, such as form input that triggers an API call. H ...

Javascript encounters difficulty in converting timestamp to a date format

I am utilizing this particular function export const getDate = (stamp: string) => { console.log(stamp) //1581638400000 let date : any = Date.parse(stamp) console.log(date) //NaN let month = date.getMonth() let day = date.getDay() ...

The Vuetify treeview displayed all objects as open, even though I had not enabled the "open-all" option

Currently, I am configuring Vuetify's treeview component for my project. When I clicked on the folder objects within the treeview, every object opened up without me setting the 'open-all' option. My project is based on vue cli 3 and my ESLi ...

Leveraging HTML Page Variables in Google Tag Manager for Enhanced Merchant Code Integration

I'm currently in the process of incorporating Google Merchant Code via GTM on a product checkout/thank you page. The Google Merchant code is : <script> window.renderOptIn = function() { window.gapi.load('surveyoptin', function() { ...

Importing Jquery into the head of a Yii2 page

I am working on my Yii2 application and have a script that requires jQuery to be loaded in the header of the page. I am aware that there is a parameter that can be configured within AppAssets.php : public $jsOptions = [ 'position' => &bs ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Utilizing variables as parameters inside a JavaScript function

I searched high and low but couldn't find a clear solution to my question. I tried various recommendations without success. Currently, I am working on a script utilizing AJAX, JavaScript, PHP, and MySQL. The goal is to create a functionality where up ...

How can we assign identical names to multiple textboxes generated by a loop?

I have a dynamic creation of multiple textboxes or textfields in JSP using a for loop. The quantity is determined at runtime based on a condition, so I can't specify the exact number. Each textbox has an onFocus event that triggers a function such as ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

Discover a term that is repeated multiple times within a single object

Consider this HTML: <div> <p>TEST TEST</p> <p>TEST</p> </div> How can I highlight all instances of the word TEST with just one button click? Currently, I am using a JavaScript function that applies bold styling to the ...

Assessing special characters in JavaScript string literals

Let's examine the code below: var a = '\\555'; var b = '\555'; console.log(a, b); // outputs \555 -5 In this code snippet, variable a contains an escaped back-slash, while variable b has an escaped character w ...