Javascript: Issue with loading image resource onto a specific div element

Seeking guidance on how to display the actual image resource on a div tag:

Here is the script in full:


var smileys = [];
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";

function RegExpEscape(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function replaceEmoticons(str) {
  for (var key in smileys) {
    var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
    var str2 = "<img src='images/smileys/" + smileys[key] + "'/>";
    //alert(re);
    //alert(str2);
    var inputName = document.getElementById("input");
    alert(inputName);
    str = str.html().replace(re, str2);
  }
  return (str);
}

var delay = (function() {
  var timer = 0;
  return function(callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

update();

function update() {
  $('#result').text(replaceEmoticons($('#input').val()));
}

$('#input').keyup(function() {
  delay(update, 250);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h4>Input :</h4>

<textarea id="input">
  Hello how are you all doing today? :)
</textarea>

<hr>
<h4>Result :</h4>

<div id="result">
</div>

Upon inspecting the element, no errors were detected in the console! Appreciate any assistance.

Answer №1

Keep in mind that the javascript code runs before the DOM finishes loading. After the page loads, the code executes and if #input doesn't exist yet, issues may arise. Make sure to place it within a $(document).ready function, or use an onload event.

 $(document).ready(function() {

      //your code here

 });

UPDATE

Check out this fiddle: https://jsfiddle.net/aoaugpaf/

Answer №2

When looking at this function:

 function replaceEmoticons(str) {
        for (var key in smileys) {
            var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
            var str2 = "<img src='images/smileys/" + smileys[key] + "'/>";
            //alert(re);
            //alert(str2);
            var inputName = document.getElementById("input");
            alert(inputName);
            str = str.html().replace(re, str2);
        }
        return (str);
    }

The issue arises when using the html() method on str since it is the value of an input as indicated here:

 $('#result').text(replaceEmoticons($('#input').val()));

To resolve this, simply discard the html() method and the code will function correctly.

For reference, I have created a fiddle for you.

Answer №3

When using $().val(), the return type is a string which does not have the .html() method available

Make amendments to the replaceEmoticons function:

 updatedString = updatedString.replace(pattern, newString);

Here is a successful example: http://jsfiddle.net/3f72djLp/

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

Edit content on the fly using ajax (add information to database)

I have a question that pertains to both UX and technical aspects. I am currently creating a list using ajax and PHP. I am unsure whether it is advisable to manipulate the DOM before the backend processes are complete. What potential issues could arise if ...

Next.js allows for passing dynamically loaded server-side data to all components for easy access

(I've recently started working with Next.js and inherited a project built using it, so please forgive me if this is something obvious that I'm missing) I have a set of data that needs to be loaded server-side on each request. Initially, I had im ...

Unable to relocate the cursor to an empty paragraph tag

Wow, I can't believe how challenging this issue is. My current project involves implementing the functionality for an enter key in a content editable div. Whenever the user hits enter, I either create a new p tag and add it to the document or split t ...

What is the process for accessing and modifying cookies in a local file:/// HTML document?

What is the most effective method for reading/writing cookies in a local file:/// HTML document using JavaScript or jQuery? I attempted the following: function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate( ...

Transforming Lines with ThreeJS

I have created a rotating cube in ThreeJS that is made up of multiple particles. These particles belong to an array called 'particles' and are part of a group named 'group' which rotates around the origin on all axes (x, y, z). My goal ...

The parameter being passed in the JSON request is empty within the WCF Service function

I have been trying to send a list of confirmations to a server using Ajax from jQuery. However, I am facing an issue where the data is being sent but the service on the server side does not receive the list. The web method expects two parameters - a strin ...

Is there a way to position the button at the bottom right corner of my div box?

Having trouble positioning the button in the bottom-right corner of the parent div? I attempted using float: right;, but it ended up outside of the box. How can I keep the button within the box and align it to the bottom-right corner? If you have a solutio ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

Interactive chat feature with live updates utilizing jQuery's $.Ajax feature for desktop users

I came across a script for real-time chat using $.ajax jQuery, but it only refreshes my messages. Here's an example scenario: I type: Hello to You, and I see this message refreshed. You reply: Hey, in order to see your message, I have to manually refr ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

Utilizing shared components with withStyles and material ui components

I'm currently working on a project using React, TypeScript, and Material UI. Here is the layout I have: <MuiThemeProvider theme={muiTheme}> <My Component/> </MuiThemeProvider> Within my component, the code looks something ...

The AJAX request I'm making is not behaving as I anticipated when returning JSON data

I'm currently working on building an ajax call to compare my database and automatically update a div if any changes are detected. JavaScript is still quite new to me, especially when it comes to dealing with JSON data. I suspect the issue lies in ho ...

Disappearing a menu list while zooming in on a page: The art of vanishing navigation

[QUESTION] Is there a way to make the Menu List disappear when zooming in on a webpage? For example: <-- Normal Page [No Zoom] --> [Logo] Profile Gallery Guestbook <-- Zoom In 120% --> [Logo] Profile Guestbook <-- Zoom In 150% --> ...

Can anyone suggest a method to block the execution of Javascript commands in the console?

Regarding the inquiry mentioned in the question title. Is it possible to prevent individuals from executing functions on my webpage using the console, even though it is not necessary? I have experimented with various methods, and the code below represent ...

The correct pattern must not be matched by ng-pattern

Within the ng-pattern attribute, we can define a specific pattern for a field to match. Is there a way to indicate that the field should NOT match the specified pattern? For instance: <input type="text" ng-pattern="/[*|\":<>[\]{}`()&a ...

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

Tips on sorting objects by comparing them to array elements

I have an array called myarrays and an object named obj. I need to filter the object by comparing the elements of the array with the keys of the object. If you want to see the code in action, you can check it out on StackBlitz: https://stackblitz.com/edit ...

What is the correct way to reuse sub-dependencies using NPM?

This inquiry primarily centers around the usage of react-admin, as indicated by the tags, but could also be applicable in other scenarios. In our case, we are utilizing react-admin which relies on @material-ui/core. This grants us the ability to incorpora ...

Transforming a 3D perspective scene into a 2D orthographic HUD scene using THREE.js

I am working on a 3D scene with objects positioned very far away, utilizing a perspective camera for the main view and an orthographic camera for a 2D Heads-Up Display (HUD): this.scene = new THREE.Scene(); this.hud = new THREE.Scene(); this.camera = new ...