Switching the navbar image with HTML and JavaScript when clicked

Looking to change the image upon clicking on any of the navbar items.

Emulating the navigation bar behavior from this website :

This is my current progress :

The HTML file :

<html lang="en">
    <head>
        <meta charset="utf-8" />       
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
        <link rel="stylesheet" type="text/css" href="StyleSheet.css" />
        <script src="scripts/jquery-1.11.3.min.js"></script>
        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
        <!--JS Scripts-->
        <script src="scripts/onClick.js"></script>        

        <title>Title</title>
    </head>
    <body>
        <div id="page-container">
            <div id="header">
                <h1><a id="name" href="Link_1.html">Test</a></h1>
            </div>
            <div id="slides-zone">
                <img id="image" src="images/1.jpg" alt="1" />
            </div>
            <nav class="navbar navbar-inverse">
                <div class="container-fluid">
                    <ul class="nav navbar-nav">
                        <li class="selected"><a href="Link_1.html" onclick="testFunction();">Link 1</a></li>
                        <li><a href="Link_2.html">Link 2</a></li> 
                    </ul>
                </div>
            </nav>        
        </div>

    </body>
</html>

My script to switch images upon clicking a nav item :

var testFunction = function () {

    var element = document.getElementById('slides-zone');
    var img_to_replace = document.getElementById('image');

    var new_img = document.createElement("img");
    new_img.setAttribute('src', 'images/2.jpeg');
    new_img.setAttribute('alt', 'image_2');
    new_img.setAttribute('id', 'image')
    element.replaceChild(new_img, img_to_replace);

    return true;
}

Hoping for a Javascript-only solution, without the use of any framework.

Appreciate any help! Thanks

Answer №1

Let me give this a shot

body {
  background-color: #000;
}
img {
  width: 800px;
  height: 400px;
  margin-left: auto;
  margin-right: auto;
}
#slides-zone {
  width: 800px;
  height: 400px;
  overflow: hidden;
}
<script>
  function changeImage() {
    document.getElementById("theImage").src = "http://www.musicmatters.ie/images/volunteer2.jpg";
  }

  function swapImage() {
    document.getElementById("theImage").src = "http://www.musicmatters.ie/images/bara4.jpg";
  }
</script>;

<body>
  <div id="page-container">
    <div id="header">
      <h1><a id="name" href="#">Test</a></h1>
    </div>
    <div id="slides-zone">
      <img id="theImage" src="http://www.musicmatters.ie/images/bara2.jpg" />
      <img id="theImage" src="http://www.musicmatters.ie/images/bara4.jpg" />
    </div>
    <nav class="navbar navbar-inverse">
      <div class="container-fluid">
        <ul class="nav navbar-nav">
          <li class="selected" onclick="changeImage();"><a href="#">Link 1</a>
          </li>
          <li onclick="swapImage();"><a href="#">Link 2</a>
          </li>
        </ul>
      </div>
    </nav>
  </div>

</body>

UPDATE: With a few lines of jquery, you could easily toggle between the images

      $(function(){
  $(".img-swap").live('click', function() {
    if ($(this).attr("class") == "img-swap") {
      this.src = this.src.replace("_off","_on");
    } else {
      this.src = this.src.replace("_on","_off");
    }
    $(this).toggleClass("on");
  });
});

Simply name your files xyz_off.jpg and xyz_on.jpg etc...

Answer №2

Implementing the use of onclick with an anchor tag can be a bit challenging. One way to approach it is by making the following modifications...

<a href="#" onclick="testFunction();">Link 1</a>

Adjust the JavaScript code to...

return false;

instead of

return true;

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

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

"When running next build, NextJS fetch() function throws an error indicating an invalid URL, but everything works fine when using

Currently, I am in the process of developing a NextJS React application and attempting to retrieve data from my server by using the following line of code: let data = await fetch('/api/getAllAlumniInfoList').then(res => res.json()) Interestin ...

How to position the navigation bar to the right using bootstrap

I have been experimenting with moving the navigation bar to the right side of the screen in bootstrap4 by using float: right; on the nav a element, but it doesn't seem to be having any effect. I am developing my project using a codepen app. Here is t ...

I'm a beginner in React Native and I'm attempting to display a "Hello World" text when the button is pressed. Unfortunately, the code below is not

''' import { StyleSheet, Text, View, SafeAreaView, TouchableOpacity, Button } from 'react-native' import React from 'react' const handlePress = () => { <View> <Text> Greetings universe ...

Whenever I include "border:0" in the styling of my hr element, a significant number of hr elements fail to appear on the screen

I have been experimenting with using hr elements to divide sections of my web page. Here is a snippet of the CSS code I am using: hr{ content: " "; display: block; height: .1px; width: 95%; margin:15px; background-color: #dfdfdf; ...

initiate changes to the application's style from a component nested within the app

I'm looking to update the background color of the entire page, including the app-nav-bar, when I'm inside a child component. When I navigate away from that component, I want the default style to be restored. Any suggestions on how to achieve this ...

Exploring the Diversity of Forms with Ajax and JQuery

$(document).ready(function () { $("#addrow").click(function () { var newRow = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" ...

The ball refuses to fall into the designated boxes

I designed a basic webpage featuring 3 boxes that, when clicked on, trigger the dropping of a ball into them. Below is the code I used: <!DOCTYPE html> <html> <head> <script type="text/javascript"> function popup (n) { ...

What is the best way to send an inline SVG string to my controller?

I am trying to send an inline svg string along with some other properties to my controller. When I replace the svg string with a normal string like "blabla", it successfully reaches my controller. However, with the actual svg string, it never makes it to ...

Equalizing the width of the border to match the width of the text

After designing a menu using a website builder with custom CSS, I found that the HTML code generated automatically by the builder needed some tweaking. Upon inspecting the code, I discovered the following structure: <div class="elementor-container elem ...

What is the best method for uploading images and form content simultaneously in a Vue application?

How can I simultaneously upload images and form content? Is it possible to upload both to the client first and then to the server together with the form content? I'm looking to submit the form content along with the image to the server in one go when ...

What is the best way to read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

Which HTML Editing Software is Best for Me?

As a college student, I have completed multiple web development and design courses. Throughout the past few years, I have utilized various tools such as PHPStorm, Visual Studio Code, Notepad++, SublimeText3, and Atom. Although I don't necessarily hav ...

What is the best way to retrieve an ng-model parameter within a controller?

I'm working on implementing a PUT method in my controller and need to bind the new value back to it. I've tried: <div ng-app="myApp" ng-controller="personCtrl"> <form> First Name: <input type="text" ng-mod ...

Images displayed on cards using BOOTSTRAP

I'm interested in creating cards with categories such as Men, Women, and Kids. I envision these cards to have a design similar to the ones shown here. My goal is for users to be able to click on one of the cards and be directed to either the Men or W ...

Encountering a mongoose error when attempting to use the push()

var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var SongSchema = new Schema({ name: {type: String, default: 'songname'}, link: {type: String, default: './data/train.mp3&a ...

What is causing my radio button event to activate when a separate radio button is selected?

I have implemented the code below to display "pers" and hide "bus," and vice versa. JQuery: $('input[name="perorbus"]').click(function() { if ($(this).attr('id') == 'bus') { $('#showbus&apo ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

Initiating the onclick event for Input/Form

<form method="POST" onsubmit="return false;"> ... <input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);"> ... </form> Is there a way to trigger the onclick event of this INPUT eleme ...

The UPDATE query failed to make any changes to the data stored in the MySQL

Currently I am developing an application using express.js. In my project, I have incorporated the "mysql" add-on (https://www.npmjs.com/package/mysql). The issue I am facing is while sending an UPDATE query to the server and receiving a response that shows ...