I've CMS, which renders a markup in such a way where I can't add any additional id, class or events to elements.
In such a way I have to add them programmatically. The task is simple:
1). Find element by class name and add to its successor,(img) id name
2). add onClick attribute to it
3). execute script onClick (should swap the image and href's name (max 3 images))
JSFiddle
Here is a piece of markup:
<div class="single-image text-center to_change_inner">
<div class="content">
<div class="single-image-container">
<img class="img-responsive" src="https://picsum.photos/200/300">
</div>
</div>
</div>
<div>
<a id="btn-1559300726188">Click</a>
</div>
And here is a JQuery:
jQuery(function($) {
element1 = $('.to_change_inner').children('img'); //find() also doesn't work
element1.id="imgClickAndChange";
if (element1.addEventListener) {
element1.addEventListener("click", changeImage, false);
} else {
if (element1.attachEvent) {
element1.attachEvent("click", changeImage);
}
}
});
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://picsum.photos/200/300")
{
document.getElementById("imgClickAndChange").src = "https://picsum.photos/20/30";
}
else
{
document.getElementById("imgClickAndChange").src = "https://picsum.photos/200/300";
}
}
window.addEventListener('load', function(){
document.getElementById('btn-1559300726188').setAttribute("onclick", "imgClickAndChange(); return true;");
});
jQuery objects are not DOM elements, they're sets of DOM elements.
To set an attribute on all elements in the set, use attr: element1.attr("id", "imgClickAndChange")
To set a property, use prop: element1.prop("id", "imgClickAndChange") (id happens to be the property reflecting the id attribute; src is also both an attribute and a reflected property).
To add an event handler, use on: element1.on("click", changeImage).
In general, setter methods in jQuery set them on all elements in the set, and getter methods get from the first element in the set (but there are exceptions).
If for any reason you need to directly access the DOM element(s) in the set, you can do that with brackets notation like with an array.
More in the API docs and the learning center.
According to your HTML, you have an error here:
element1 = $('.to_change_inner').children('img'); //find() also doesn't work
The comment is incorrect, find would be what you want there, not children:
var element1 = $('.to_change_inner').children('img'); // Doesn't work
console.log(element1.length); // 0, no matching elements
var element1 = $('.to_change_inner').find('img'); // Works
console.log(element1.length); // 1, there was a matching element
<div class="single-image text-center to_change_inner">
<div class="content">
<div class="single-image-container">
<img class="img-responsive" src="https://picsum.photos/200/300">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
That code also seems to be falling prey to what I call The Horror of Implicit Globals, you need to declare element1.
Use this:
jQuery(function($) {
element1 = $('.to_change_inner img');
element1.attr('id',"imgClickAndChange");
element1.on('click',function(){changeImage();})
});
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://picsum.photos/200/300")
{
document.getElementById("imgClickAndChange").src = "https://picsum.photos/20/30";
}
else
{
document.getElementById("imgClickAndChange").src = "https://picsum.photos/200/300";
}
}
window.addEventListener('load', function(){
document.getElementById('btn-1559300726188').setAttribute("onclick", "imgClickAndChange(); return true;");
});
Related
I am trying to create a jquery code which can wrap an img tag with a link:
My code is like this:
http://prntscr.com/iuw6hc
I will paste my HTML here but basically it is a loop of many items showing within each col.
<div class="car-item gray-bg text-center first" style="height: 357px;">
<div class="car-image">
<img class="img-responsive" src="http:///wp-content/uploads/2018/03/20180214_090633-265x190.jpg" alt="" width="265" height="190">
<div class="car-overlay-banner">
<ul>
<li><i class="fa fa-link"></i></li>
I am trying like this:
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
wrapped = true;
var gURL = $('.car-overlay-banner').find('a').attr('href');
$(".img-responsive").wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
wrapped = false;
$(".img-responsive").parent().replaceWith(original);
}
});
Trying to use a href of car overlay to apply to the image too.
jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
<div id="parent">
<div id="child"></div>
</div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() {
$("#imgLogo").wrap('');
});
In this example, I have used ID as selector but you can use class selector to find all the images with same class and then wrap them with tag. You can also assign target="_blank" in the above tag to open the link in new window.
I think you need code like this?
var wrapped = false;
var original = $(".img-responsive");
$(".img-responsive").click(function(){
if (!wrapped) {
var wrapped = true;
// find link href in .car-image(img-responsive's parent)
var gURL = $(this).parent().find('a').attr('href');
// use $(this) instead of $(".classname") to apply link only clicked image
$(this).wrap("");
}
});
$(".img-responsive").click(function(){
if (wrapped) {
var wrapped = false;
$(this).parent().replaceWith(original);
}
});
I am trying to toggle a div when its name is clicked.
I have multiple coupls like that in my page, and I want it to work as
"when <p id= "d2"> is clicked => <div id="d2"> is toggled".
I tried those functions:
$(document).ready(function(){
$("p").click(function(){
$("div#" + $(this).attr('id')).toggle();
});
});
function rgt() {
//document.body.innerHTML = "";
var id = "d" + this.id;
var situation = document.getElementById(id).style.display;
if (situation == "none") {
situation = "block";
}
else {
situation = "none";
}
}
function showHide(theId) {
if (document.getElementById("d" + theId).style.display == "none") {
document.getElementById("d" + theId).style.display = "block";
}
else {
document.getElementById("d" + theId).style.display = "none";
}
}
I can't make it Work!!! Why is it?
the browser says:"no 'display' property for null"...
I will be more than happy to solve it with simple jquery
Ensure Your id Attributes Are Unique
Assuming that your id attributes are unique, which they are required to be per the specification:
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
You should consider renaming your id attributes to d{n} and your paragraphs to p{n} respectively as seen below :
<button id='p1'>p1</button> <button id='p2'>p2</button> <button id='p3'>p3</button>
<div id='d1'><pre>d1</pre></div>
<div id='d2'><pre>d2</pre></div>
<div id='d3'><pre>d3</pre></div>
which would allow you to use the following function to handle your toggle operations :
$(function(){
// When an ID that starts with P is clicked
$('[id^="p"]').click(function(){
// Get the proper number for it
var id = parseInt($(this).attr('id').replace(/\D/g,''));
// Now that you have the ID, use it to toggle the appropriate <div>
$('#d' + id).toggle();
})
});
Example Using Unique IDs
You can see an interactive example of this approach here and demonstrated below :
Consider Using data-* Attributes
HTML supports the use of data attributes that can be useful for targeting specific elements through jQuery and associating them to other actions. For instance, if you create an attribute on each of your "p" elements as follows :
<button data-toggles='d1'>p1</button>
<button data-toggles='d2'>p2</button>
<button data-toggles='d3'>p3</button>
and then simply change your jQuery to use those as selectors :
$(function(){
// When an element with a "toggles" attribute is clicked
$('[data-toggles]').click(function(){
// Then toggle its target
$('#' + $(this).data('toggles')).toggle();
});
});
Is this you are looking?
$("#p1").on("click", function() {
$("#d1").toggle();
});
js fiddle: https://jsfiddle.net/Jomet/09yehw9y/
jQuery(function($){
var $toggles = $('.divToggle');
var $togglables = $('.togglableDiv');
$toggles.on('click', function(){
//get the div at the same index as the p, and toggle it
$togglables.eq($toggles.index(this)).toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="divToggle">Show Me 1</p>
<p class="divToggle">Show Me 2</p>
<p class="divToggle">Show Me 3</p>
<div class="togglableDiv">Weeee 1</div>
<div class="togglableDiv">Weeee 2</div>
<div class="togglableDiv">Weeee 3</div>
Minimal approach using classes. This solution assumes the order of the p elements in the dom are in the same order as the divs are in the order. They do not have to be contiguous, but the order does matter with this solution.
ids are not the droids you are looking for.
An id needs to be unique. If you want to classify something one would suggest to use classes. You can actually use serveral of them for some fancy stuff. How about something like this:
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
Straight forward. Every element that is a switch or switchable gets the class toggle. Each pair of switch and switchable(s) gets an additional identifier (like one, two, ...).
Simple JScript Implementation:
Now how about not using JQuery to work with that? Sure it i$ handy, but it hides all that neat stuff one would eventually like to learn her/himself!
var myToggle = {};
(function(module) {
"use strict";
(function init() {
var elements = document.getElementsByClassName("toggle");
var element;
var i = elements.length;
while (i) {
i -= 1;
element = elements[i].className;
elements[i].setAttribute("onclick", "myToggle.swap(\"" + element + "\")");
}
}());
module.swap = function(element) {
var couple = document.getElementsByClassName(element);
var i = couple.length;
while (i) {
i -= 1;
if (couple[i].style.display === "none" && couple[i].tagName === "DIV") {
couple[i].style.display = "block";
} else if (couple[i].tagName === "DIV") {
couple[i].style.display = "none";
}
}
};
}(myToggle));
<p class="toggle one">one</p>
<div class="toggle one" style="display:none">content one</div>
<p class="toggle two">two</p>
<div class="toggle two" style="display:none">content two 1</div>
<div class="toggle two" style="display:none">content two 2</div>
var myToggle = {} is the object we use to keep our little program contained. It prevents that our code conflicts with other declarations. Because what if some plugin on our site already declared a function called swap()? One would overwrite the other!
Using an object like this ensures that our version is now known as myToggle.swap()!
It may be hard to follow how it got to that name. Important hint: something looking like this... (function() { CODE } ()) ...is called an immediately-invoked function expression. iffy! It's a function that is immediatly executed and keeps its variables to itself. Or can give them to whatever you feed it in the last ()-pair.
Everything else is as verbose as can be... no fancy regular expressions, hacks or libraries. Get into it!
So I have this HTML:
<div class="tip-box">
<div class="tip-title" onclick="toggleTip()">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
And this Javascript:
function toggleTip() {
$(this).siblings(".tip-content").toggleClass("hidden");
}
Hopefully it's obvious what this is supposed to do, but it doesn't work. Using .siblings() just doesn't seem to work in this way.
What's the correct solution for this? To get the next sibling of a certain type or with a certain class and then hide/show it?
You can use Jquery function.
<div class="tip-box">
<div class="tip-title">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
$(document).ready(function(){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
you can also use this
<div class="tip-box">
<div class="tip-title" onclick="toggloTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
<script>
function toggloTip(elm) {
$(elm).siblings(".tip-content").toggleClass("hidden");
}
</script>
You can use pure javaScript with nextElementSibling property of node something like below,
I suppose you want do this operation with siblings.
function getChildrens(n, selector) {
var nodes = [];
while (n.nextElementSibling != null) {
if (n.nextElementSibling.hasOwnProperty('classList')) {
if (n.nextElementSibling.classList.contains(selector)) {
//return n.nextElementSibling;
nodes.push(n.nextElementSibling);
}
}
n = n.nextElementSibling;
}
return nodes;
};
function getSiblings(n, selector) {
return getChildrens(n, selector);
}
function toggleTip(elem) {
var siblings = getSiblings(elem, "tip-content");
if (siblings.length > 0) {
for (var i = 0; i < siblings.length; i++) {
siblings[i].classList.toggle("hidden");
}
}
}
.hidden {
display: none;
}
<div class="tip-box">
<div class="tip-title" onclick="toggleTip(this)">
<h2>Tip 1</h2>
</div>
<div class="tip-content hidden">
<p>Tip 1 content</p>
</div>
</div>
Here is another non JQuery answer.
To get the next element sibling use:
var nextElement = element.nextElementSibling;
To get the previous element sibling use:
var previousElement = element.previousElementSibling;
To get the element index use:
var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);
If you are at the first element the previousElementSibling value will be null.
If you are at the last element the nextElementSibling value will be null.
How about this JavaScript:
$(function(){
$('.tip-box').on('click', '.tip-title', function(){
$(this).next('.tip-content').toggleClass('hidden');
});
});
Remove the idea of working with onclick attributes when you use jQuery.
None of the previous answers, not even that serial-upvoted one ;), actually explains the problem and why their solutions work.
The problem is that an inline onclick handler does not pass on its current context. Inside the onclick="" JavaScript code this is the element clicked. Once you call a global function (like your toggleTip), that context is lost. The this the function receives is window and not the element.
The usual quick fix, for raw JavaScript code, is to pass this as a parameter to the global function.
e.g.
onclick="toggleTip(this)"
and receive a parameter in the function like this:
function toggleTip(element) {
$(element).siblings(".tip-content").toggleClass("hidden");
}
However, as you are using jQuery, inline event handlers are actually a bad idea. They separate the event registration from the event handler code for no reason and do not allow for multiple event handlers, of the same type, on the same element. They also bypass the rather cool event bubbling system jQuery uses.
The preferred alternative, with jQuery, is to use jQuery to select the element and jQuery to connect the event in one step:
jQuery(function($){
$('.tip-title').click(function(){
$(this).siblings(".tip-content").toggleClass("hidden");
});
});
As you only want the element that follows, and potentially will add more pairs, the better option would be using nextAll and first(), with the same jQuery filter, instead of siblings:
e.g.
jQuery(function($){
$('.tip-title').click(function(){
$(this).nextAll(".tip-content").first().toggleClass("hidden");
});
});
Or, of you can guarantee it is the next element, use next as #Tim Vermaelen did (with or without the selector makes no difference, so might as well leave it out):
jQuery(function($){
$('.tip-title').click(function(){
$(this).next().toggleClass("hidden");
});
});
Note: In this example jQuery(function($){ is a DOM ready event handler which is the rather handy shortcut version of $(document).ready(function(){YOUR CODE});, which also passes a locally scoped $ value. For those that mistake this code for an incorrect IIFE, here is a working example: http://jsfiddle.net/TrueBlueAussie/az4r27uz/
So I have a mini slide menu in my website there is a menu you can choose what you want to read. There are points to click, when u clicked it the point get a red background.
But there is a problem.
When i click one point and then an other point the first clicked point have to lose his background.
Here is my HTML:
<div id="slide_button" onClick="clicked(this);"><dir class="button_1"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_2"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_3"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_4"></dir></div>
<div id="slide_button" onClick="clicked(this);"><dir class="button_5"></dir></div>
Here is my JS:
function clicked(slide_button) {
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
HERE IS AN EXAMPLE ON FIDDLE.
My "QUESTION IS" what i have to do to solve that?
What should I pay attention?
First you need to fix your HTML becaue your id values aren't unique. In fact, you don't even need id values, so you should use "slide_button" as a class. You can then use it to select all the buttons:
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
<div onClick="clicked(this);" class="slide_button"><dir></dir></div>
The CSS needs to be changed now so "slide_button" is a class selector, instead of an id selector:
.slide_button {
display: inline-block;
}
As for clearing the background, clear all of them before coloring the selected one red:
function clicked(slide_button) {
var buttons = document.getElementsByClassName('slide_button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].getElementsByTagName('dir')[0].style.backgroundColor = '';
}
slide_button.getElementsByTagName('dir')[0].style.backgroundColor = 'red';
}
jsfiddle
This uses just JavaScript with no JQuery, but if you are using JQuery, you might as well use it here. The code is a lot shorter and easier to follow.
Here's a JQuery version:
$(function() {
$('.slide_button').click(function() {
var $button = $(this);
$button.children(':first').css({ backgroundColor: 'red' });
$button.siblings().children(':first').css({ backgroundColor: '' });
});
});
Note: This registers a click-handler, so you can get rid of the "onclick" attirbutes.
jsfiddle
You have to select all other points and set their background to none.
Or remeber which point is selected and on select another just remove background on last and remeber current point, then set its background to red.
See fiddle: http://fiddle.jshell.net/399Dm/5/
At first id should be unique per element.
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
<div class="slide_button"><dir class="button"></dir></div>
Second, you should store reference of clicked element if you want later remove background color, and instead of inline event handlers or binding all elements would be better if you use event delegation.
Demonstration
(function () {
"use strict";
// getting parent node of divs, due to bind click event. then
var ele = document.querySelector(".slide_button").parentNode,
prev = null; // store previous clicked element
ele.addEventListener("click", clickHandler); // event handler.
function clickHandler(e) {
var t = e.target; // get target of clicked element
// filter by target node name and class. edit: removed class checking
if (t.nodeName.toLowerCase() === "dir") {
// checking value of prev !== null and it's not same element.
if (prev && prev !== t) {
prev.style.backgroundColor = "";
}
prev = t; // store clicked element
t.style.backgroundColor = "red";
}
}
}());
I have fixed the fiddle so that it works hopefully as you plan.
http://jsfiddle.net/399Dm/8/ There you go!
var forEach = function(ctn, callback){
return Array.prototype.forEach.call(ctn, callback);
}
function clear(element, index, array) {
element.getElementsByTagName("dir")[0].style.backgroundColor="";
}
function clicked(slide_button) {
forEach(document.getElementsByClassName("slide_button"), clear);
//.style.backgroundColor="";
slide_button.getElementsByTagName("dir")[0].style.backgroundColor="red";
}
I had a slightly different method than #atlavis but a similar result.
http://fiddle.jshell.net/2AGJQ/
JSFIDDLE DEMO
jQuery
$('.slide_button').click(function(){
$('.slide_button dir').css("background-color", "inherit");
$(this).find('dir').css("background-color", "red");
});
HTML - Your markup is invalid because you have duplicate ids. Make them classes as below instead.
<div class="slide_button" >
<dir class="button_1"></dir>
</div>
<div class="slide_button">
<dir class="button_2"></dir>
</div>
<div class="slide_button">
<dir class="button_3"></dir>
</div>
<div class="slide_button">
<dir class="button_4"></dir>
</div>
<div class="slide_button">
<dir class="button_5"></dir>
</div>
CSS change
.slide_button {
display: inline-block;
}
If you can look at the following jsfiddle, I used jQuery to get what you want.
I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>