jfrosty jfrosty - 1 month ago 11
jQuery Question

Adding and removing variable on href element?

I have 2 boxes with

data-attributes
for 2 different pages. When you click
A
the
href
should change from
index.html
to
index.html/a
, and if you click
B
it should remove
/a
and add
/b
.

I've been able to change the variable, but not when you click another box. So I get
index.html/a/b
. I guess it should be toggle between the two boxes.

HTML

<div class="box" data-id="a"></div>

<div class="box" data-id="b"></div>

<a class="link" href="index.html>Click Me</a>


JS

$('.box').on('click', function() {

var box_id = $(this).data('id');

if($(this).data('id') === box_id) {
$('.link').attr('href', function() {
return.href + '?' + box_id;
});
}
});

Answer

The following will grab the current href from the link and remove either /a or /b and append the ID of the box you clicked.

(I added styles to the boxes to make them visible in the snippet)

var link = $('a');

$('.box').on('click', function () {
  var id = $(this).attr('data-id');
  var newHref = link.attr('href').replace(/\/(a|b)/, '') + '/' + id;
  link.attr('href', newHref);
  $('#result').text(newHref);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-id="a" style="width:100px;height:100px;background:red"></div>

<div class="box" data-id="b" style="width:100px;height:100px;background:blue"></div>

<a class="link" href="index.html">Click Me</a>
                      
<div id="result"></div>