JavaScript Click Event Not Functioning

I am attempting to create an interactive feature where clicking on any image will either reveal a clear version of the picture if it is blurred, or blur the picture if it is clear.

The current issue I am facing is that when I click on a blurred image, it becomes clear, but clicking on it again does not re-blur the image. Additionally, clicking on a clear image does not blur it as intended.

Below is the code snippet in question:

<script>

    window.onload = init;

    function init(e) {
        var img = document.getElementsByTagName("img"); 

        img[0].onclick = unblur;
        img[1].onclick = unblur;
        img[2].onclick = unblur;

     }

    function unblur(e) {

        var imageId = e.target.id;  
        var img = document.getElementById(imageId);

        var imageSource = img.src; 

        var clearImg = imageSource.substring(0, imageSource.length - 8);

        var unblurredImg = imageId.concat('.jpg');   
        var blurredImg = imageId.concat('blur.jpg'); 

        if (img.src == unblurredImg) {  
            img.src = blurredImg;
        } else {
            img.src = unblurredImg; 
        }   
    } 

</script>

</head>

<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">

</div>

</body>
</html>

After experimenting with different conditions inside the unblur() function, I realized that switching the order of these conditions had unexpected outcomes. For example...

if (img.src == unblurredImg) {  
    img.src = blurredImg;
} else {
    img.src = unblurredImg;  
}   

This change caused no response when clicking on a blurred image, whereas the previous code would at least reveal the cleared image. The only alteration made was switching the sequence of the conditions.

Why did this adjustment lead to different results? Can you spot why there may be a difference?

Answer №1

Your provided example contains several errors. Please refer to the Code Snippet below for a correct implementation:

Regarding your query:

// <- why not just img.onclick = unblur ??

The reason is that using document.getElementsByTagName results in an array of elements. Thus, it is necessary to iterate through each element in order to assign the onclick event handlers individually.

(function(document) {
  var array = document.getElementsByTagName("img");
  for (var i = 0; i < array.length; i++) {
    array[i].onclick = toggleBlur;
  }

  function toggleBlur(event) {
    var img = event.target;
    var oldSrc = img.src; // Saved for display in the console
    if (img.src.endsWith("blur.jpg")) {
      img.src = img.id + ".jpg";
    } else {
      img.src = img.id + "blur.jpg"
    }
    console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
  }
})(document);
<body>
  <div id="pics">
    <img id="zero" src="zero.jpg">
    <img id="one" src="one.jpg">
    <img id="two" src="twoblur.jpg">
  </div>
</body>

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

What's the reason for the alert not functioning properly?

I am curious about the distinction between declaring a variable using var. To explore this, I tried the following code: <body> <h1>New Web Project Page</h1> <script type="text/javascript"> function test(){ ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error: Ex ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

jQuery counter no longer updates when scrolling

I'm having trouble with my jQuery counting function when using the scroll feature on a specific div ID. The numbers freeze if I keep scrolling before they finish updating on the screen. Whenever I scroll to the defined div ID, the counting function k ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

What occurs when a file being imported is also importing a file that the first file is already importing?

I have three JavaScript files with dependencies: - main.js <- dependencies: module.js, helper.js - module.js <- dependencies: helper.js - helper.js <- no dependencies main.js and module.js both import from helper.js, while main.js imports from ...

Creating a table and populating its cells with values all within the confines of a single function

This section of code aims to create 3 arrays by extracting values inputted by the user from a popup menu in the HTML file. These values are then utilized to populate the table displayed below. var arrM = new Array; var arrT = new Array; var ar ...

How can I utilize the pick parameter in nuxtjs3 useFetch for selecting arrays or performing a deep pick?

Currently working on my nuxtjs3 project, where I am extracting data from an API. Specifically using jsonPlaceholder for this task. Extracting data from a single object is not a problem: const { data: useFetchOnly } = await useFetch('https://jsonplace ...

What is the best choice for code design patterns in a nodejs environment? What are the key considerations for creating a well-

Although I have a background in games development using C/C++/C#, I have recently delved into automated testing and now I am eager to learn more about backend development. My current project involves creating a platform for automated backups, building fr ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Jasmine - effectively mimicking an object that utilizes a constructor

Currently, I am attempting to simulate the native WebSocket in a jasmine test for Angular. I have successfully spied on the constructor and `send` function, but I am struggling to figure out how to fake a call of `onmessage`. The WebSocket has been extrac ...

Error message: When initiating AJAX requests in ASP.NET, the function is not defined for undefined

I recently followed a tutorial on creating AJAX requests for CRUD operations in an AngularJS application. However, upon trying to perform an AJAX request to retrieve data from the database, I encountered the following error when launching my application: ...

Is Eval really as bad as they say... What alternative should I consider using instead?

After making an ajax request, a JSON array filled with user inputs is returned to me. The inputs have already been sanitized, and by utilizing the eval() function, I can easily generate my JavaScript object and update the page... However, there lies a dil ...

Mapping two arrays in JavaScript involves iterating through each element of the arrays

I'm having trouble displaying the content of two arrays contained within an object. When I map over RType.information.Type, I can display the content of the "Type" array. However, I am unable to display both Type[] and Price[]. I've tried various ...

Is it advisable to use npm devDependencies in a production environment?

While reviewing the package.json file for one of our products at work, I noticed that the SDK uses socket.io for a crucial function even though socket.io-client is listed as a devDependency. Despite this discrepancy, the SDK works flawlessly for our clie ...

React components to separate static PDF pages

I have successfully implemented a feature in my React App that allows me to export a long page in PDF format using html2canvas and jsPDF. The code snippet for exporting the page is as follows: html2canvas(document.body).then((canvas) => { var img ...

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

Encountering a node.js issue

Hi there, I keep encountering this error message. Can someone explain what it means? I'm not very skilled in coding, so I would appreciate any assistance :) Best regards logon fail: 65, sessionID: 6343803 events.js:85 throw er; // Unhandled & ...