When a hyperlink is clicked, an image appears in the div

Can someone help me with a javascript method that can display an image in a div based on which href link is clicked?

I've started writing some code, but I think it needs further development.

<script type="  ">
function changeImg(){
    var image1 = new Image();
    image1.src='car.png'
    var imghol = document.getElementById("imageHolder");
    var elements = document.getElementById("FS");
    if(elements.onclick = function()){
        imghol = image1;
    }
</script>

<div class="ADS2"><h2>Vehicle Part</h2><p>Please select a part you wish to find;
<div class="vertical_menu">
<ul>
<li><a id="FS" href="#home" onclick="changeImg">Front Side</a></li>
<li><a id="RS" href="#news">Rear Side</a></li>
<li><a id="S" href="#contact">Side</a></li>
<li><a id="US"href="#about">Under Side</a></li>
<li><a id="I" href="#about">Interior</a></li>
</ul>
</div>
<div class="imageholder">

</div>
</div>

Answer №1

Keep it simple and efficient with the following code:

<script type="text/javascript">
function swapImage(img){
  var placeholder = document.getElementById("imageHolder");
  placeholder.src = img;
}
</script>

<div class="ADS2">
    <h2>Vehicle Part</h2>
    <p>Select a part to locate:</p>
    <div class="vertical_menu">
        <ul>
            <li><a id="FS" href="javascript:" onclick="swapImage('car.jpg');">Front Side</a></li>
            <li><a id="RS" href="javascript:" onclick="swapImg('rear.png')">Rear Side</a></li>
            <li><a id="S" href="javascript:" onclick="swapImg('caside.png')">Side</a></li>
            <li><a id="US" href="javascript:" onclick="swapImage('under.png')">Under Side</a></li>
            <li><a id="I" href="javascript:" onclick="swapImg('interior.png')">Interior</a></li>
        </ul>
    </div>
    <div class="imageholder"><img id="imageHolder" /></div>
</div>

Answer №2

utilize the following

XHTML

<a onclick="switchImage('pic1.png')">Link 1</a>
<a onclick="switchImage('pic2.png')">Link 2</a>
<a onclick="switchImage('pic3.png')">Link 3</a>
<a onclick="switchImage('pic4.png')">Link 4</a>
.....
<div class="imageholder">
<img id="change_img_target" />
</div>

ECMAScript

function switchImage(url) {
    document.getElementById("change_img_target").src = url;
}

Answer №3

If you prefer, you can also use jQuery to accomplish this task. Just remember to include the jQuery library in your project. :)

Here is an example of how you can achieve this:

<a href="#" onclick="return changeImg('pic1.png')">Link 1</a>
<a href="#" onclick="return changeImg('pic2.png')">Link 2</a>

<div id="div">

</div>

Simply add the following jQuery code at the end of your HTML file:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        function changeImg(url) {
            var image = "<img src='url' />";
            $("#div").html(image);
        }
    });
</script>

Answer №4

@ Naveen,

If you're looking for a solution, you have two options to choose from:

Solution 1:

<script type="text/javascript>
  function preloader()
  {
      var imgs = ['chart1.jpg','chart2.jpg','chart3.jpg','chart4.jpg','chart5.jpg'];

      var container = document.getElementById('photos');

      var docFrag = document.createDocumentFragment();

      imgs.forEach(function(url, index, originalArray) {
          var img = document.createElement('img');

          img.src = url;

          docFrag.appendChild(img);
      });

      container.appendChild(docFrag);
  }
</script>

<body onload="preloader();">
  <div>
    <table width="100%" style="height: 100%;" border="0">
      <tr>
        <td>
          <p id="photos" onclick="preloader()" />
        </td>
      </tr>
    </table>
  </div>

Solution 2:

function preloader()
{
    var imgs=['chart1.jpg','chart2.jpg','chart3.jpg','chart4.jpg','chart5.jpg'];

    var container = document.getElementById('photos');

    for (var i = 0, j = imgs.length; i < j; i++) {
        var img = document.createElement('img');

        img.src = imgs[i];

        container.appendChild(img);
    }
}

For more assistance, check out this helpful link:

How to add a list of images to the document from an array of URLs?

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

I'm looking to create a JavaScript function that will extract each element from a div and then apply a corresponding CSS block to activate it

My goal was to create this function using Flask, but it seems that only JavaScript is capable of achieving it. This is my first attempt at coding it. Here's the code snippet: const navSlide2 = () => { const burger = document.querySelector(&apos ...

`Incompatibility issue between HTML, CSS and Chrome browser`

There seems to be an issue with the left menu not displaying properly on the website in Google Chrome. Interestingly, it appears correctly aligned at the bottom of the menu in Firefox (blue), but in Chrome, it is positioned in the middle. Despite the co ...

Recording the descending data points (excluding the dragged positions) from the bootstrap slider

I am struggling with the implementation of the BootStrap Slider from this source: I have encountered an unusual requirement. I need to capture the values of the slider only when the user stops dragging it, not during the process of sliding. In other words ...

When you add new objects to VueJS Store, they are simply substituted for the existing objects

Currently, I am encountering an issue with the code snippet below that is used to insert a new object into the 'items' array. The problem lies in the fact that whenever a new object is added, it ends up replacing the content of the previously add ...

Creating a responsive layout that sets the window height to 100% and automatically adjusts sibling divs when the content within parent divs exceeds the defined height

<section> <div class="section-wrap"> <h1>page1</h1> </div> </section> <section> <div class="section-wrap"> <h1>page2</h1> </div> </section> My attempt at impleme ...

What is the best way to update a specific value in an object without affecting the rest of

Below is a data object: { name: "Catherine Myer", age: 23, birthday: "august" } If I want to pass this data as a prop to a component, but also change the age to 24, how can I do that? <NextPage data={author.age = 24}/> The ...

Only one submenu can be opened at a time & click to close

I am encountering an issue with my list and submenus. When I click on List 1, submenu 1 opens but if I then click on List 2, submenu 2 opens while submenu 1 remains open. However, when I click on List 2 again, instead of just closing submenu 2, it toggles ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...

How to utilize PHP $_SESSION variables with jQuery for error handling and page redirections

I am currently working on a project where I need to access PHP session variables using jQuery in order to redirect users using jQuery instead of PHP. When a user logs in, a PHP script is executed to check their logged in and registered status in the databa ...

The list retrieved via ajax appears to be void of any elements, despite the array size being accurately reflected

I am attempting to pass a List from the controller to an ajax function in order to display images in a modal carousel. The process begins when I click on an image, which triggers the ajax function to send a value. This value is then used to call a C# metho ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

Sticky sidebar following a complete-page header

I recently added a fixed sidebar to my website: However, I'm facing an issue where the sidebar appears in front of my full-page header when I set its position to fixed. What I actually want is for the sidebar to start after the header as if it were p ...

Displaying incorrect text format on a TextView using Html.fromHtml()

Within my application, there is a string that represents a mathematical expression: String s = "log<small><sub>(log<small><sub>(log<small><sub>3<small><sup>2</sup></small></sub></small&g ...

Flexbox that adjusts to any browser height, ensuring full responsiveness

I am exploring the world of flexbox with the goal of creating a responsive layout consisting of 3 items that adjust seamlessly to different devices such as smartphones, tablets, and desktop computers. The layout should stack the items on top of each other ...

Creating a dropdown feature for menu items in Vue when the number or width of items exceeds the menu bar's limits

I am working on a navigation bar that displays menu items as tabs. One issue I am encountering is when the number of menu items exceeds the space available, I need to move the excess items into a dropdown menu (showmore) using Vue. Here is an example of t ...

What is the best way to update the state of a particular slider component?

When trying to update the value of a specific slider during the onChange event, I noticed that it was affecting all sliders instead. Is there a way to target and set the state of only one slider during this event? Here's what I've attempted so f ...

Modify URL parameters using history.pushState()

Utilizing history.pushState, I am adding several parameters to the current page URL after performing an AJAX request. Now, based on user interaction on the same page, I need to update the URL once again with either the same set of parameters or additional ...

Changing the border color of an HTML input is easy with these simple steps:

As part of an educational project, I am developing a login-registration system using HTML, CSS, and PHP. The system will include various HTML text boxes and elements. My goal is to change the border color of a textbox to green when I input something into ...

How can I retrieve the HEX code of a color from an image when hovering or clicking?

Is there a way to retrieve the hexadecimal code of a pixel within an image displayed on a webpage using jQuery, without relying on the canvas element? I am specifically interested in obtaining the actual color code of the image itself, not the background c ...