Modify the text in a paragraph by clicking on a link using JQuery and HTML

I'm attempting to implement a straightforward action, but I'm facing some challenges. My navigation bar consists of a few links followed by a text section. What I aim for is that when I click on a link, the paragraph of text should change to reflect the corresponding link.

I have experimented with various approaches (please excuse my rusty skills in JQuery and javascript) but nothing seems to work!

I am open to exploring new methods to achieve the desired outcome.

var ptext;

   $(document).ready(function(){
      ptext = $("#pchange");
      $(".one").click(function(){
        ptext.html("text1");
      });
      $(".two").click(function(){
        ptext.html("text2");

      });
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
* {
    box-sizing: border-box;
}

body {
    font-family: Arial, Helvetica, sans-serif;
}

h2 {
    color: white;
}

/* Style the header */
header {
    background-color: #2B547E;
    padding: 30px;
    text-align: center;
    font-size: 35px;
    color: white;
}

/* Create two columns/boxes that float next to each other */
nav {
    float: left;
    width: 30%;
    height: 300px; 
    background: #43BFC7;
    padding: 20px;
}

/* Style the list inside the menu */
nav ul {
    list-style-type: none;
    padding: 0;
}

article {
    float: left;
    padding: 20px;
    width: 70%;
    background-color: #f1f1f1;
    height: 300px;
}

/* Clear floats after the columns */
section:after {
    content: "";
    display: table;
    clear: both;
}

/* Style the footer */
footer {
    background-color: #2B3856;
    padding: 10px;
    text-align: center;
    color: white;
}

@media (max-width: 600px) {
    nav, article {
        width: 100%;
        height: auto;
    }
}
</style>


<header>
  <h2>Voice of the Theatre</h2>
<img src="http://pngimg.com/uploads/world_map/world_map_PNG14.png" width="100px" height="60px">
</header>

<section>
  <nav>
    <ul>
      <li><a class="one" href="#">EMEAR</a></li>
      <li><a class="two" href="#">AMER</a></li>
    </ul>
  </nav>
  
  <article>
    <h1>London</h1>
    
    <div id="pchange">
    
    </div>
    
<ul>
  <li>Update 1 </li>
  <li>Update 2</li>
  <li>Update 3</li>
</ul>


<h1>America</h1>
<ul>
  <li>Update 1 </li>
  <li>Update 2</li>
  <li>Update 3</li>
</ul>


  
  </article>
</section>

<footer>
  <p></p>
</footer>

Answer №1

To disable the functionality of a link, you have two options: either remove the href attribute from the anchor tag or add event.preventDefault() to prevent the default behavior.

Additionally, if you simply want to change the text content of an element, use .text() instead of .html().

var ptext;

$(document).ready(function() {
  ptext = $("#pchange");
  $(".one").click(function(event) {
    event.preventDefault();
    ptext.text("text1");
  });
  $(".two").click(function(event) {
    event.preventDefault();
    ptext.html("tex2");

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
  * {
    box-sizing: border-box;
  }
  
  body {
    font-family: Arial, Helvetica, sans-serif;
  }
  
  h2 {
    color: white;
  }
  /* Style the header */
  
  header {
    background-color: #2B547E;
    padding: 30px;
    text-align: center;
    font-size: 35px;
    color: white;
  }
  /* Create two columns/boxes that floats next to each other */
  
  nav {
    float: left;
    width: 30%;
    height: 300px;
    /* only for demonstration, should be removed */
    background: #43BFC7;
    padding: 20px;
  }
  /* Style the list inside the menu */
  
  nav ul {
    list-style-type: none;
    padding: 0;
  }
  
  article {
    float: left;
    padding: 20px;
    width: 70%;
    background-color: #f1f1f1;
    height: 300px;
    /* only for demonstration, should be removed */
  }
  /* Clear floats after the columns */
  
  section:after {
    content: "";
    display: table;
    clear: both;
  }
  /* Style the footer */
  
  footer {
    background-color: #2B3856;
    padding: 10px;
    text-align: center;
    color: white;
  }
  /* Responsive layout - makes the two columns/boxes stack on top of eac...
 
</footer>

Answer №2

In order to enhance the functionality, you have the options of adding href="javascript:void(0)", event.preventDefault(), or event.stopPropagation(); you can select any one method.

Your script is responsible for modifying the HTML content. It functions with .html() or .text(), but using .text() is recommended because it specifically refers to the inner text instead of elements in the HTML.

Initially, when you click on the nav ul li a button, extract the text and update the target element's text accordingly.

All systems are operational...

Appreciate your assistance

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

Encountering an issue with resolving a local variable during the execution of a test with Protractor

I'm currently learning about async calls in protractor as a newbie to the tool. I am struggling to figure out how to handle a boolean variable that I set to true if any test case fails and the execution goes to the catch block for a promise. Below is ...

How plupload can seamlessly transition to the next upload after completing one

Using plupload 1.5.7 and the jQuery Queue Widget, I've noticed that after completing an upload, the Add files and Start Upload buttons disappear, replaced by a label saying Upload 1/1 files. Unfortunately, this means I can't add more files witho ...

Adding Php code to a Wordpress form can be done by creating a custom

I'm struggling to incorporate a PHP code into a WordPress form that I created. Despite trying three different PHP plugins, I haven't been successful. Can anyone advise on where and how to properly integrate the PHP code in WordPress and call it t ...

The Ajax success function is failing to trigger after receiving a 200 network response

I have a basic HTML page that loads jquery 3.3.1 and an external script file called script.js. I am using a simple node http-server to serve the static page. The data.json file is also in the same folder as the HTML file. However, even though the network c ...

What is the process for extracting specific elements from a JSON object and incorporating them into a SELECT dropdown as options?

My json file contains a wealth of information. Here is a snippet: { "ListProductsResponse": { "Products": [{ "VatAmount": 0, "VatFormat": "Percent", "Bonus": { "AdditionalValue": 0, ...

What is the process for adding color to HTML elements?

Is there a way to assign unique random colors to each individual p tag in ReactJS? function App() { return ( <div> <p style={{ color: "#7fbd73" }}>Hi</p> <p style={{ color: "#3a82e4" }}>Hello</p> < ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Step-by-step guide on populating a state using an array

I am having trouble populating a list within a state using the set method, as the state remains empty App.js // Initiates the secrets word game const startGame = () => { // pick word and pick category const { word, category } = pickWordAndCat ...

Mastering the art of obtaining XPaths through Selenium WebDriver

While working on test automation for a section of Outlook Web App, I focused on checking a designated test mailbox that receives emails from our company. I needed to verify specific texts within an email using Assert, but encountered difficulty in identify ...

Update the Material UI input field value using an external JavaScript script

Imagine I find myself exploring an online form that utilizes Material UI components, for instance, this example link. I am interested in automatically filling the input fields with a specific value using JavaScript in the console: for (input of document.g ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Alignment of Bootstrap responsiveness shifted to the left rather than the center

My HTML Code: <div class="gridrow" id="eventsrow"> <div class="gridcard" id="eventcard" style="float:left;width:100%;height:100%;margin-bottom:0.5rem;background-color:white"> <div class="event container"> <div clas ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Outdated jQuery script no longer functioning (Wordpress)

I recently updated a WordPress site to Version 5.7.2 and now two of the custom Metaboxes are not functioning as expected. The issue seems to be related to the outdated jQuery version used by the Metaboxes. To address this problem, I installed a Plugin cal ...

Tips on introducing a random pattern into a Javascript gaming experience

To kick off the game, let's generate a pattern randomly. Follow these steps: -Include a function that generates the pattern. (Hint: JavaScript's Math.random function might come in handy) -Invoke your new function from the startGame function I&a ...

When the page is refreshed, reorienting axes in three.js encounters difficulties

I am currently working on a project that involves using the three.js editor source code available for download on the three.js website. As part of this project, I am required to adjust the orientation of the axes to align with standard airplane coordinate ...

Error Message: jQuery script imported successfully, however, functions are not defined

Here is my HTML code: <script type="text/javascript" src="js/myjs.js"></script> <script> ... $("#enviornment").hide().delay(1200).css({'display':'block', 'opacity':'0'}).animate({'opacity&apos ...

Retrieve the key value pair from the AJAX response

I am trying to retrieve specific values from a cross domain call to a PHP script. The response I receive is as follows: response=2&count=15&id=84546379&firstname=adsa&emailstatus= My goal is to extract the values of 'response' a ...