Preventing anchored links from leaving stored histories

2

I have a code that has two blocks on the sides and clicking on them happens a change of background color of the page, but as they are defined with 'target' that pull each element in an ordered way, the following happens, for each click will storing blank pages in the browser history, would anyone have any solution to prevent this storage in history when clicking on the blocks ?? maybe a javascript?

body{background-color:#6C9;}

*{ padding:0px; margin:0px;}
.menu{ overflow:hidden;  
}
/*Coloração do background*/
#bc1{ background-color:#6C9;
width:100%; 
position: absolute; 
z-index:-1; 
height:100%; 
left:0px; 
right:0px; 
top:0px; 
display:none; 
}
#bc2{ background-color:#00F;
width:100%; 
position: absolute; 
z-index:-1; 
height:100%; 
left:0px; 
right:0px; 
top:0px; 
display:none; 
}
#bc3{ background-color:#000;
width:100%; 
position: absolute; 
z-index:-1; 
height:100%; 
left:0px; 
right:0px; 
top:0px; 
display:none; 
}
 
/*CFG: cubos-red*/
.menu .pre_nxt{ position:absolute; 
z-index:99; 
top:45%; 
width:100%; 
height:0px;
left:0px;
}
.menu .pre_nxt a{ background-color:#F33; 
position:absolute; 
width:60px; 
height:60px;  
opacity:0.7; 
transition:all 0.3s linear;
}
.menu .pre_nxt a+a{ background-color:#F33; 
left:auto;  
right:0px;
}
.menu .pre_nxt a:hover{ opacity:1;
}
.menu .pre_nxt > div+div{ visibility:hidden;
}

/* visibilidade dos cubos red a cada click*/
.menu >s:target ~ .pre_nxt > *{ visibility:hidden;}
#bk1:target ~ .pre_nxt > *:nth-child(1){ visibility:visible;}
#bk2:target ~ .pre_nxt > *:nth-child(2){ visibility:visible;}
#bk3:target ~ .pre_nxt > *:nth-child(3){ visibility:visible;}


/*Transição ancorada ao clicar nos cubos, cor background aciona */
#bk1:target ~ #bc1{ display:block; }
#bk2:target ~ #bc2{ display:block; }
#bk3:target ~ #bc3{ display:block; }
<nav class="menu">
<s id="bk1"></s>
<s id="bk2"></s>
<s id="bk3"></s>

<div id="bc1"></div><!--verde-->
<div id="bc2"></div><!--azul-->
<div id="bc3"></div><!--preto-->


<div class="pre_nxt">
  <div><a href="#bk3"></a><a href="#bk2"></a></div>
  <div><a href="#bk1"></a><a href="#bk3"></a></div>
  <div><a href="#bk2"></a><a href="#bk1"></a></div>
</div>

</nav>

    
asked by anonymous 14.06.2018 / 22:33

1 answer

3

Use location.replace() with preventDefault() this way:

var ancs = document.querySelectorAll("a[href^='#']");

for(var x=0; x<ancs.length; x++){
   ancs[x].onclick = function(e){
      e.preventDefault();
      location.replace(this.href);
   }
}

This will prevent the browser from adding a new entry in history by canceling the click event and will apply the # anchor contained in the href .

Using jQuery:

$("a[href^='#']").click(function(e){
   e.preventDefault();
   location.replace(this.href);
});

Test here

    
15.06.2018 / 01:09