I have 4 divs next to each other, each containing a link. I want to dynamically switch the id of “current” around,
for example.
<div name="1" id="current">
<a>
link
</a>
</div>
<div name="2">
<a>
link
</a>
</div>
<div name="3">
<a>
link
</a>
</div>
<div name="4">
<a>
link
</a>
</div>
How can I dynamically change which one is the current one when the link is clicked?
Don’t do this. Element IDs should not change based on the state of the web page. Use another attribute instead, like
class="current".If you’re using jQuery, which I highly recommend, you can do this as follows:
To make this code work, you need to add
class="tab"to your<div>elements. This is a good idea especially if you have other<div>elements on the page. If you do this, the current tab would then have an attributeclass="tab current". jQuery knows how to handle this properly.Also, I would consider using the
idattribute instead of thenameattribute, and giving your<a>tags ahrefattribute so that browsers will show them as clickable elements. For example:Here’s an example of how to include this script (assuming that you have JQuery saved as a file
jquery.jsin the same directory as the HTML page):A couple of notes about that:
Really, it’s better to put your site’s JavaScript in a separate file and include it with
<script type="text/javascript" src="filename.js"></script>, but including it “inline” like I’ve done is fine for small projects or just playing around with stuff.The
$(function() { ... });is shorthand for$(document).ready(function() { ... });, which means the code inside that block will be executed as soon as the browser has finished loading the HTML document structure. For example, you don’t want your JavaScript to execute before the browser has finished downloading the rest of the page.