Reputation: 51
This is for a site that has jquery and jquery ui installed, so that might help.
Basically, I have a site with several different modal windows. The way I want to call these modals is via various anchor tags.
For instance, let's say I have modalone, with an ID of #modalone.
I have a specific anchor tag with <a href="#modalone" class="modals">
I need the code that will add a class to <div id="modalone"></div>
This way, if I have <a href="#modaltwo" class="modals">
I can add the same visibility class to <div id="modaltwo"></div>
, and modalthree, modalfour, etc etc.
Upvotes: 0
Views: 70
Reputation: 1089
//Grab all anchors (assuming modals is solely for the anchor)
var anchors = document.getElementsByClassName("modals");
//Iterate through all of them
for (var i = 0; i < anchors.length; i++) {
//Get the div with the ID of the anchor href, minus the "#" and add the class "modal"
document.getElementById(anchors[i].getAttribute("href").substr(1)).classList.add("modal");
}
If you only want to add the class when the anchor is clicked, you need to bind an onclick event handler to each anchor like so:
window.onload = function() {
//Grab all anchors (assuming modals is solely for the anchor)
var anchors = document.getElementsByClassName("modals");
//Iterate through all of them
for (var i = 0; i < anchors.length; i++) {
//Add the onclick event
anchors[i].onclick = function() {
//Our href reference is now "this"
document.getElementById(this.getAttribute("href").substr(1)).classList.add("modal");
}
}
}
Here's a JSFiddle Example: http://jsfiddle.net/CcaN8/3/
Upvotes: 1
Reputation: 3019
If you want to add the class for each element on init you can do the following:
$('.modals').each(function(index, element){
element = $(element);
$(element.attr('href')).addClass(element.attr('class'));
});
Upvotes: 0
Reputation: 1598
You can do something like this
$(".modals").click(function() {
var item = $(this).attr("href");
var itemClass = $(this).attr("class");
$(item).addClass(itemClass);
return false;
});
Here instead of .modals in the click event, you can specify anytype of identifier. Or simply create a function,
function AddVisibilityClass(elem)
{
var item = $(elem).attr("href");
var itemClass = $(elem).attr("class");
$(item).addClass(itemClass);
return false;
}
You can call this function in the anchor tags onclick method
<a href="#modalone" class="modals" onclick="AddVisibilityClass(this)">
Upvotes: 2