What is the method to prevent the background image from refreshing when clicking on the navbar?

I have designed a webpage with a navigation bar. However, when I click on a button in the navbar, the image refreshes and does not display correctly.

I attempted to show different pictures when each button in the navbar is clicked. Each button should display a unique image. I managed to create the buttons and link them to the JavaScript file successfully.

function changePhotos(e) {
  if (e.target == first) {
    document.getElementById("images").style.backgroundImage =
      'url("image' + 1 + '.jpg")';
    return;
  }
  if (e.target == sec) {
    document.getElementById("images").style.backgroundImage =
      'url("image' + 2 + '.jpg")';
    return;
  }
  if (e.targer == third) {
    document.getElementById("images").style.backgroundImage =
      'url("image' + 3 + '.jpg")';
    return;
  }
}

let first = document.getElementById("pic1");
let sec = document.getElementById("pic2");
let third = document.getElementById("pic3");

first.addEventListener("click", changePhotos);
sec.addEventListener("click", changePhotos);
third.addEventListener("click", changePhotos);
body {
  height: 100vh;
  width: 100vw;
}

.container-fluid {
  position: relative;
}

#bar {
  position: relative;
  background-color: aqua;
}

#images {
  position: absolute;
  height: 94%;
  bottom: 0;
  width: 100%;
}
/* Additional CSS code inserted by user */
#navigate {
  position: absolute;
  width: 100%;
  background-color: grey;
  border: 0.1px solid #000;
  border-radius: 5px;
  padding: 5px;
}

#images {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="index.css" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
  <title>CoOL wEb</title>
</head>

<body>

  <div class="container-fluid h-100">
    <div class="row" id="bar">
      <nav class="navbar navbar-expand-lg navbar-light" id="navigate">
        <a class="navbar-brand">Photos</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                              <span class="navbar-toggler-icon"></span>
                            </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link" href="" id="pic1">Pic1</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="" id="pic2">Pic2</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="" id="pic3">Pic3</a>
            </li>
          </ul>
        </div>
      </nav>
    </div>
    <div class="row" id="images">

    </div>
  </div>
  <script src="index.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

I am looking for a solution where the images do not keep refreshing but are displayed properly. Any suggestions would be appreciated. Thank you!

Answer №1

Make sure to include e.preventDefault(); at the start of your changePhotos function:

function changePhotos(e) {
  e.preventDefault();
  
  if (e.target == first) {
    document.getElementById("images").style.backgroundImage =
      'url("https://www.medicalnewstoday.com/content//images/articles/322/322868/golden-retriever-puppy.jpg")';
    return;
  }
  if (e.target == sec) {
    document.getElementById("images").style.backgroundImage =
      'url("https://pixel.nymag.com/imgs/fashion/daily/2019/06/18/18-puppy-dog-eyes.w700.h700.jpg")';
    return;
  }
  if (e.targer == third) {
    document.getElementById("images").style.backgroundImage =
      'url("https://tractive.com/static/images/product-images/tratr3g/tractive-gps-3g-dogtracker-dalmatian-dog.jpg")';
    return;
  }
}

let first = document.getElementById("pic1");
let sec = document.getElementById("pic2");
let third = document.getElementById("pic3");

first.addEventListener("click", changePhotos);
sec.addEventListener("click", changePhotos);
third.addEventListener("click", changePhotos);
body {
  height: 100vh;
  width: 100vw;
}

.container-fluid {
  position: relative;
}

#bar {
  position: relative;
  background-color: aqua;
}

#images {
  position: absolute;
  height: 94%;
  bottom: 0;
  width: 100%;
}

#navigate {
  position: absolute;
  width: 100%;
  background-color: grey;
  border: 0.1px solid #000;
  border-radius: 5px;
  padding: 5px;
}

#images {
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
 '<meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="index.css" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
  <title>CoOL wEb</title>
</head>

<body>

  <div class="container-fluid h-100">
    <div class="row" id="bar">
      <nav class="navbar navbar-expand-lg navbar-light" id="navigate">
        <a class="navbar-brand">Photos</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                              <span class="navbar-toggler-icon"></span>
                            </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
            <li class="nav-item">
              <a class="nav-link" href="" id="pic1">Pic1</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="" id="pic2">Pic2</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="" id="pic3">Pic3</a>
            </li>
          </ul>
        </div>
      </nav>
    </div>
    <div class="row" id="images">

    </div>
  </div>
  <script src="index.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

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

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

It is not possible to invoke a function within the mounted() lifecycle hook

I recently integrated a chat API into my Vue.js project for connecting to chat rooms. Upon entering a chat room page, an ajax request is triggered which then calls a function responsible for fetching the complete chat history: mounted() { $.ajax({ url: ...

Set the CSS table to have a width of 100% and ensure that the table data cells have hidden

My table has a 100% width, and some of the td elements have overflow hidden. I want to make their text appear as ellipsis when it's too long. I can achieve this with fixed td sizes, but I need them to be relative to the content. This question was fi ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

What could be the reason for Jest coverage reporting 0 branches covered in this Vue component method with Istanbul?

Take a look at this somewhat contrived Vue component: <!-- FooBar.vue --> <template> <div @click="onClick">{{text}}</div> </template> <script> export default { name: 'foo-bar', data() ...

Python Selenium: How to interact with an element nested within multiple HTML tags

Currently, I am working on automating a website using selenium webdriver in Python. However, I have encountered an issue when trying to click on a specific tag. The website that I am attempting to automate is quite old and contains numerous iframes and &l ...

Automatically triggering a click event on a div element utilizing jQuery

I've utilized jquery to create buttons that trigger events when clicked. Now, I'm looking for a way to set one of the buttons in a "clicked" state initially to show the same effect before actually clicking it. For instance, if I have a button cre ...

Using CSS, eliminate the drop-down menu from the main navigation on Squarespace

While working on my Squarespace website, I've been impressed with how the FAQ page/questions are structured. However, a drawback is that it creates a clunky drop-down menu when hovering over the FAQ tab in the main navigation. You can see an example ...

Selecting JavaScript file on change as default option

Currently, I have an HTML file that prompts the user to select an XML file when the file selection is changed. Is there a way to make it so that by default, only one file is chosen? <form id='fileSelection' action=""> <center> <in ...

What is the method for displaying an image within an HTML div element?

Is there a way to include an image inside an HTML div tag when printing a document? Here's the method I've been using: Using HTML5: <div> <img src="/images/pag.jpg" alt="pagsanghan Logo" style="opacity: .8; height:100px; width:10 ...

Angular retrieving a document collection from Firebase based on a specific field

I am trying to retrieve collection data based on the UserId field. retrieveData(){ const data$ = this.firestore.collection(this.trackerCollection,ref=> ref.where('UserId','==',"WrKDk0XSNjU20FI0EVRvADzvNHz1")).snapshotCha ...

Width of the `div` element is expanding

I'm encountering an issue where a div container is automatically stretching to the full width of the page, instead of adjusting to fit the content within it. Below is the HTML code snippet: <!doctype html> <html> <!-- Head --> <h ...

Implementing jsGrid: Appending a row with JSON information

Is there a way to dynamically insert a row in jsGrid? I found some helpful code examples at https://github.com/tabalinas/jsgrid/blob/master/demos/db.js ...

Setting the height of the Angular UI modal relative to the height of the window

I am currently working on a modal that contains a significant amount of text. My main goal is to limit the height of the modal to the size of the window, while also adding a scrollbar to the content area positioned above the OK button. Check out the Plunk ...

What is causing the animate function to hide the other div once the animation is completed?

Check out the code here http://codepen.io/kongakong/pen/wMQrBR Javascript Section: $(document).ready(function () { init(); }); function init() { $('#test').on('click', function () { $('.answer').animate({width: ...

Tips for transferring data from a controller to $scope in the MVC architecture with AngularJS

I'm a beginner when it comes to AngularJS, currently working with an MVC5 application. I have set up a module and controller in the Angular JS for this application. Within my customer controller in MVC5, I have an action called "View" where I need to ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

An internal server error has occurred within the asp.net framework, resulting in

Seeking Solution: Currently, I am in the process of developing an application where I have implemented an HTML select list to choose a category. Using AJAX web method, I am trying to retrieve items and their respective images based on the selected category ...

Is there a way to substitute the HOC with a single call and solely modify the prop?

One issue I've encountered in my project is the repetitive use of a Higher Order Component (HOC) for the header. Each time it's used, the props are set to determine whether header links should be displayed or not. My objective is to streamline th ...