By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of the page. The goal is to have the hidden image slide out from the left when any image in the table is clicked. Currently focusing on learning pure JavaScript without relying on JQuery. Any assistance would be greatly appreciated.

Below is the setup with HTML, CSS, and JavaScript:

HTML for the table:

  <table>
   <tbody>
      <tr>
      <td><img onclick="sleepFunction()" src="01.jpg" height="180" width="120"></td>
      <td><img src="02.jpg" height="180" width="120"/></td>
      <td><img src="03.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img src="04.jpg" height="180" width="120"/></td>
      <td><img src="05.jpg" height="180" width="120"/></td>
      <td><img src="06.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img src="07.jpg" height="180" width="120"/></td>
      <td><img src="08.jpg" height="180" width="120"/></td>
      <td><img src="09.jpg" height="180" width="290"/></td>
      </tr>
   </tbody>

HTML for the hidden image:

<div class = "sleepImage">
<img src = "sleeping.jpg" width= "490"/>
   </div>

CSS styling:

 .sleepImage {
float: right;
position: absolute;
top: 108px;
left: -600px;
}

Javascript snippet:

function sleepFunction() {
document.getElementsByClassName("sleepImage")[0].style.left = "300px";
}

Answer №1

update the sleepImage by changing it from a class to an id, modify your code like this

html

<div id = "sleepImage">
<img src = "sleeping.jpg" width= "490"/>
</div>

css

#sleepImage {
   /* include your styles here */
}

js

function changeSleepFunction() { 
   document.getElementById("sleepImage").style.left = "300px";
}

Answer №2

` element, create an identifier for your div (NameDiv) and modify your function as shown below:
document.getElementById("NameDiv").style.left = "300px";

Answer №3

When you use document.getElementsByClassName('sleepImage'), it will retrieve an array containing all elements with the class name sleepImage. To target the first element in the array, add an index at the end of the method call. Here's an example:

function adjustSleepImage() {
    document.getElementsByClassName("sleepImage")[0].style.left = "300px";
}

Answer №4

Upon closer observation, the code you have written is as follows:

document.getElementsByClassName("sleepImage").style.left = "300px";

It's important to note the usage of getElementsByClassName. As the name implies, it returns elements, not a single element. These elements are returned as a collection (similar to arrays), so iterating over the collection is necessary to access the specific element you want.

The correct code to use in this case is:

document.getElementsByClassName("sleepImage")[0].style.left = "300px";

Check out the demo below:

document.getElementById("myBtn").addEventListener("click", function () {
    document.getElementsByClassName("sleepImage")[0].style.left = "300px";
});
.sleepImage {
     position: absolute;
 }
<table>
   <tbody>
      <tr>
      <td><img onclick="sleepFunction()" src="01.jpg" height="180" width="120" alt="selectorImage"/></td>
      <td><img src="02.jpg" height="180" width="120"/></td>
      <td><img src="03.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img src="04.jpg" height="180" width="120"/></td>
      <td><img src="05.jpg" height="180" width="120"/></td>
      <td><img src="06.jpg" height="180" width="290"/></td>
      </tr>
      <tr>
      <td><img src="07.jpg" height="180" width="120"/></td>
      <td><img src="08.jpg" height="180" width="120"/></td>
      <td><img src="09.jpg" height="180" width="290"/></td>
      </tr>
   </tbody>
       </table>
<input type="button" value="Move Image" id="myBtn"/>
       <div class = "sleepImage">
<img src = "sleeping.jpg" width= "490" alt="sleepImage"/>
   </div>

I hope this clarifies things for you!

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 is the best way to include numerous optional parameters within a single route in Express?

Been a huge fan of Stackoverflow and finally decided to ask my first question here! I've been working on a JavaScript Express project, trying to figure out if it's possible to achieve the desired functionality under a single GET request. Struggli ...

How can you retrieve input radio button values using javascript or ajax and display or hide a button accordingly?

I've created a form that includes radio input buttons and a textarea field as follows: <input type="radio" value="2" id="order_status"> Review <input type="radio" value="1" id="order_status"> Accept <input type="radio" value="2" id="or ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

On Linux systems, Node.js in JavaScript interprets strings as objects only

I'm encountering an issue with my Discord.io bot. I am attempting to run it on a Linux server, but the Linux version of Node.js keeps treating the contents of a string as a separate object, leading to the following TypeError: TypeError: Object IT&apo ...

NodeJs backend encounters undefined object due to FormData format request sent from Angular frontend

Never encountered this issue before despite having used this method for a long time. (Angular Frontend) const myFormData = new FormData(); myFormData.append("ok", "true"); this.http.put(my_Express_backend_url, myFormData); (Express ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...

How to send parameters to Bootstrap modal using a hyperlink

I need help confirming the deletion of a datatable row using a Bootstrap modal dialog. When a user clicks on the delete link, I want a modal to appear asking for confirmation. Here is my code: <c:forEach items="${equipes}" var="equ"> ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

Is there a way to toggle a single Reactstrap Collapse component?

Currently, I am working on a Next.JS application that displays a list of Github users. The goal is to have each user's information box toggle open and close when clicked, using Reactstrap's Collapse component. However, the issue I'm facing i ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

Developing in Java Script with ENVDTE involves adding a new project to an existing solution and placing it in a designated sub-folder for organization purposes

Currently, I am working on developing a Visual Studio extension for a new C++ project template using Visual Studio 2010. The approach I am taking involves utilizing the .vsz template method and customizing the default.js code to suit my requirements. Withi ...

Vue function displays 'undefined' message

Although many posts on this topic exist already, I am struggling to understand what is going wrong (even after searching extensively here and on Google). I have created my interceptor like this, but I keep receiving an error message stating "This is undef ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Is the p tag not becoming absolute from the bottom even when set to position: absolute?

My p tag in the section properties of div class="sf sf_2 won't align to 0 px from the bottom of the div. It seems to move 0px from the top, right, and left but not bottom. I've tried changing its position property and where it's nested, but ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not. In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax). I want the Markers to revert back to their original color when th ...