Steps for eliminating the #id from a URL page

Can someone assist me in removing or hiding my #id from the URL browser?

For example:

  • My menu1 targets "#p1"
  • My site is "mysite.com/index.htm"
  • When I click menu1 on my browser, it will show as "mysite.com/index.htm#p1"

I want my id to not show on the URL browser, just "mysite.com/index.htm" without the appended #p1.

#p1:target { background: red;}
#p2:target{ background: green;}
#p3:target{ background: blue;}
#p4:target{ background: yellow;}
#p5:target{ background: coral;}
#p6:target{ background: skyblue;}

ul{list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}
li {float: left;}

li a{ display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;}

li a:hover {
    background-color: #111;
}
<div id="menu">
    <input type="checkbox" id="tbl-menu"/>
    <label for="tbl-menu"><img src="drop.png" height="40px"  width="40px" alt=""></label>
        <nav class="nav">
        <ul class="tombol">
        <li class="tombolmenu">
            <a class="t1" href="#p1">Menu1</a></li>
            <li><a class="t2" href="#p2">Menu2</a></li>
            <li><a class="t3" href="#p3">Menu3</a></li>
            <li><a class="t4" href="#p4">Menu4</a></li>
            <li><a class="t5" href="#p5">Menu5</a></li>
            <li><a class="t6" href="#p6">Menu6</a></li>
         </ul>
         </nav>    
      </div>

<!-- My page target -->

<div id="p1">  Page1 </div>
<div id="p2">  Page2 </div>
<div id="p3">  Page3 </div>
<div id="p4">  Page4 </div>
<div id="p5">  Page5 </div>
<div id="p6">  Page6 </div>

Answer №1

Although this question may be considered dated in Internet years, I wanted to share my solution, which is inspired by Janmejay Agrawal's approach.

Essentially, it modifies the default behavior of a hyperlink to create a smooth scrolling effect to the desired element.

This script is written in "vanilla" JS and is compatible with most web browsers.

//Retrieve all hyperlink elements
var links = document.getElementsByTagName("a");

//Iterate through the array of links
Array.prototype.forEach.call(links, function(elem, index) {
  //Check if the hyperlink points to an id
  var elemAttr = elem.getAttribute("href");
  if(elemAttr && elemAttr.includes("#")) {
    //Replace the default action with smooth scrolling to the target element
    elem.addEventListener("click", function(ev) {
      ev.preventDefault();
      //Smooth scroll to the target element by finding the href's target id using regex
      document.getElementById(elemAttr.replace(/#/g, "")).scrollIntoView({
          behavior: "smooth",
          block: "start",
          inline: "nearest"
          });
    });
  }
});

If there are any errors in this code, please feel free to bring them to my attention!

Answer №2

If you're looking to implement smooth scrolling for in-page links, one effective method is to create a custom function rather than relying solely on the browser. Here's an example:

$("a[href^='#']").click(function(e){
  e.preventDefault();
  var targetElement = $($(this).attr('href'));
  
  if(targetElement.length) {
    $('html, body').animate({
      scrollTop: targetElement.offset().top
    }, 800);
  }
});

Using this approach not only hides the '#id' from the URL but also provides a visually pleasing scrolling effect. Give it a try and see if it works 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

Is there a way to restrict the orientation of a UIWebView using JavaScript or HTML?

Currently, I am working on HTML content for an iPad application. The challenge at hand is locking the UIWebView's content to portrait mode. Despite having already submitted the app to Apple, I have only come across a solution in this question, which s ...

Querying data from a promise and embedding it in a JSON object in AngularJS

Attempting to retrieve data from a promise within a JSON object for the first time has presented me with a challenging task. The typical approach looks something like this: Service JS app.factory("dataService", ["$http", function ($http) { fu ...

Vue router is unable to render or mount the component at the root path

I am currently working on a webpage using vue, vue-router, and laravel. I have encountered an issue where the Home component is not being rendered in the router-view when I access localhost/myproject/public_html/. However, if I click on the router link to ...

What is the best way to create an arrow that tracks the browser window, but only goes as far as the end of its designated container

Currently, I am facing a challenge in implementing a scroll down arrow. While this is typically a simple task, it has proven to be a bit more complex this time around. The complexity arises from the fact that my customer desires a homepage with an image of ...

Angular version 8.2 combined with Firebase can result in errors such as those found in the `./src/app/app.module.ngfactory.js` file towards the end of the process when attempting to build with

My first time posing a query on this platform, and certainly not my last. The issue at hand involves the ng-build --prod process failing to complete and throwing errors in my Angular 8.2.14 application. I've integrated Firebase into my project succes ...

The 404 error is handled by the express application before continuing to other routes. Some routes may not be recognized by the express.Router module

Shown below is the content of app.js: var express = require('express'); var routes = require('./routes/index'); app = express(); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

Remove image files from a directory with jQuery without relying on PHP or AJAX

Did you know that JQuery code is capable of executing unlink operations like PHP without using AJAX or a PHP file? For instance, if you wish to delete or unlink the file "aaa.jpg" located in the folder www.myproject.com/images/, you can achieve this by s ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

Can you guide me on how to adjust the correct view on my controller?

After successfully inserting data using jQuery AJAX within a modal, I am encountering a problem where the view appears differently than expected. Below is a snippet of my AjaxCrudController: public function store(Request $request) { // $create = ...

An issue occurred while the request was being transported or processed, resulting in Error code 10 at Path /wardeninit

Currently, I am attempting to pass an object (specifically the contents of a row from a sheet) to an apps script template. The screenshot displays the actual row. https://i.stack.imgur.com/IzMrn.png The function in my apps script consists of the followin ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

Determine the location of a character based on its index position

Is it feasible to identify the precise x and y coordinates of the character at position 24 (e.g., '-') in this overflowing multi-line text? ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...

Pass a notification to a separate function

Issue Looking for a way to send an 'event' to another function using jQuery. The goal is to prevent the removal of a table row before executing certain treatments, and then remove the row. I want to insert a modal window in between these actions ...

Refine objects based on their properties without removing them from the dataset

I have a specific object structured as follows: var myObj: { 2:"None", 20:"A", 31:"A", 32:"A", Social:"B", Method:"None" } My goal is to retrieve the object without the properties 'Social' and 'Method'. Initia ...

Automatically populate the checkbox with the specified URL

Is it possible to pre-fill a checkbox in an HTML form using the URL? For example, if we have a URL like www.example.com/?itemname=sth Would there be a similar method to pre-select a checkbox via the URL? <ul class="list-group"> <li c ...

Tracking mouse positions across an HTML document

I've been working on a project inspired by the voxel painter example on the three.js page. In this particular example, the mouse coordinates are utilized to move a roll-over helper that indicates where a box will be placed upon click. mouse.set((even ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

My web browser doesn't recognize my JavaScript as actual JavaScript?

HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="/js/grabber.js" type="text/javascript"></script> <script type="text/javascript"> $(docu ...