Show/hide div on click if div class names match - javascript

I have two sets of divs — one that is the 'main' div and one that is the 'extra' div. Both of these have classes that are brought in via the CMS.
What's the best way of showing/hiding (preferably slideToggle) each div, on click, that corresponds to the div clicked?
<div class="each-business-content-main" data-id="group-1"></div>
<div class="each-business-content-main" data-id="group-2"></div>
<div class="each-business-content-extra group-1"></div>
<div class="each-business-content-extra group-2"></div>
These 'group-1' or 'group-2' classes aren't known in advance so can't be hard-coded in. Essentially I'm wondering how, if you click on one div it shows another div (as long as they share the same class name).
I've tried this so far:
$('.each-business-content-main').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
jQuery('.each-business-content-extra').slideUp();
jQuery('.each-business-content-extra .' + id).slideDown();
});
But I'm guessing hrefs and id might come in useful? Or some other data-id...

If you assign a data attribute to your divs it makes this pretty easy:
<div class="each-business-content-main group-1" data-group="1">main 1</div>
<div class="each-business-content-main group-2" data-group="2">main 2</div>
<div class="each-business-content-extra group-1" data-group="1">extra 1</div>
<div class="each-business-content-extra group-2" data-group="2">extra 2</div>
$('.each-business-content-main').click(function () {
$('.each-business-content-extra.group-' + $(this).data('group')).slideToggle();
});
jsFiddle example

Have you tried replacing this:
jQuery('.each-business-content .' + id).slideDown();
...with this:
jQuery('.each-business-content #' + id).slideDown();
jQuery selects classnames as .classname and IDs as #id.

Try
$('.each-business-content').click(function () {
var that = $(this);
$('.each-business-content').each(function () {
if ($(this) === that) {
$(this).slideUp();
} else {
$(this).slideDown();
}
});
});

Can you try this code at jsFiddle? Don't need group 1 and group 2, I use index instead of the name of the id. Is that all right for you?
$('.each-business-content-main').on('click', function (e) {
$('.each-business-content-extra').(':eq(' + $(this).index() + ')').slideDown();
$('.each-business-content-extra').not(':eq(' + $(this).index() + ')').slideUp();
});

Related

Efficient jQuery/JS - avoiding copy-paste the same code again & again

I need to write an efficient code in order to keep it simple & code file small, also I want to use the knowledge I hopefully get from here in future codes.
UPDATE: Just to be clear - my example is fixed "buttons" on browser window side & if you click on one of them, it takes you to div with same ID (look at code below).
IMAGE:
MY CODE EXAMPLE:
//Smooth Scroll Menu Links
jQuery('.div1').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
//I have to copy-paste it 1000 times & only change the ".div1" to something else
//Note that I need a solution with different class names, not "div1", "div2" etc but e.g "location", "potato", "car" etc.
How to make this code working without writing same lines for every single div?
There got to be a way to get class from item you click & then scroll to item with same name ID, right? Or any other way to keep codes shorter in that kind of situations - otherwise it's just copy-paste-huge-file fest.
You can give each button a class so you can catch them all, than go to the element you want to scroll to by looking at the attribute of the clicked button :)
HTML
<div class="buttons" data-scroll="div1">div1</div>
<div class="buttons" data-scroll="div2">div2</div>
<div class="buttons" data-scroll="div3">div3</div>
<div class="content" id="div1">some content</div>
<div class="content" id="div2">some content</div>
<div class="content" id="div3">some content</div>
JS
$('.buttons').on('click', function(e) {
e.preventDefault();
var scrollTarget = $(this).data("scroll");
scrollme(scrollTarget);
function scrollme(target) {
$('html,body').animate({scrollTop:$("#"+target).offset().top}, 800);
}
});
example: http://jsfiddle.net/7gd66kr1/1/
try this i hope will work with you :
jQuery('div').on('click', function(e) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:jQuery(this.hash).offset().top-100}, 800);
});
note that : this function will aplay on all divs in page
I think there are more than an unique solution. If you don't want to modify your HTML, then you need a condition to determine if the clicked element is an "active" one:
jQuery('div').on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
if(scrollto.length > 0) {
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
}
});
If you "can" modify your HTML, it's wise to add some attribute to the "active" elements (the ones that are buttons), so you know they scroll the page, or put them inside a container. The attribute you add may be a class or any other valid attribute (I recommend "rel", but might be "data" as spotted by #Iliya Reyzis , who selects by class and scrolls to "data") and select them by it:
<div class="div1" rel="mybutton">div1</div>
jQuery("[rel='mybutton']").on('click', function(e) {
var id = $(this).attr('class');
var scrollto = $('#' + id);
e.preventDefault();
jQuery('html,body').animate({scrollTop:scrollto.offset().top-100}, 800);
});
Hope it helps!!

Jquery: how to know which element was clicked?

I have an html code with 5 divs. They all have the same class, and different IDs.
Then, within javascript I have this:
$(".pics").click(function() {
alert("hey!");
});
where .pics is the name of the class of all the divs. The idea is that when I click on any of them, a certain script should be triggered, but I also want to know which one of the divs was clicked upon.
How do you go about it?
Thanks.
Assuming your ids are like this:
<div class="pics" id ="pic1">...</div>
<div class="pics" id ="pic2">...</div>
<div class="pics" id ="pic3">...</div>
<div class="pics" id ="pic4">...</div>
<div class="pics" id ="pic5">...</div>
Then in your javascript:
$(".pics").click(function() {
alert("You are clicking "+$(this).attr('id'));
});
And you should see something like this:
You are clicking pic1
Try this:
$(".pics").click(function() {
alert("hey!" + $(this).attr("id"));
});
You can get this information from the target of the click event, as shown here.
$(".pics").click( function (e) {
var clickedElement = e.target;
})
this refers to that element.
$(".pics").click(function() {
var me = $(this);
alert(this.id);
});

Dynamically Replacing Content with Javascript and Links

http://jsfiddle.net/bUjx7/42/
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'>
</script>
<script type='text/javascript'>
$(document).ready(function () {
$('.fieldreplace a').click(function () {
$('#fieldmatch, .fieldgame').hide();
var region = $(this).data('region');
$('#' + region).show();
});
});
</script>
I'm trying to make it so clicking one link will replace content in all the cells, and not, as it is, in just one cell.
Help?
You can replace the contends of all tds like?
$('#tableId td').html('content to update on all cells');
There are several problems in your code.
I see you have specify id="fieldgame1" many times, remember id should be unique for every element.
You would make use of class selector instead of id selector for selecting all elements.
Now, you would make the cell content with different classes, and use class selector to hide/show them.
HTML
<div class="fieldmatch" >2-5</div>
<div class="fieldgame1" >1-6</div>
<div class="fieldgame2" >6-1</div>
<div class="fieldgame3" >2-5</div>
Css
.fieldgame1, .fieldgame2, .fieldgame3 {
display:none;
}
JavaScript
$(document).ready(function () {
$('.fieldreplace a').click(function () {
$('#fieldmatch, .fieldgame').hide();
var region = $(this).data('region');
$('#' + region).show();
});
});
Code example on : http://jsfiddle.net/bUjx7/44/

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

JQuery - work with divs

I want to set another class for the clicked menu-part. Clicking generates url with #NAME. Here is my menu:
<div id="head_menu">
<div name="order" id="menu_part">make order</div>
<div id="menu_part">portfolio</div>
<div id="menu_part">contacts</div>
<div id="menu_part">vacancies</div>
<div id="menu_part">about company</div>
</div>
I need to add class: 'menu_choosed' for clicked part. Here is my jquery-code:
$(document).ready(
function()
{
currentPage = window.location.hash;
$('#head_menu>div').each(
function()
{
if( currentPage == $(this).hash )
{
$(this).addClass("menu_choosed");
}
}
)
}
)
I really don't know, how to filter values :( Help, please.
The easy way:
$(document).ready(
function()
{
currentPage = window.location.hash;
$('#head_menu a[href=' + currentPage + '] div').addClass('menu_choosed');
}
);
There are a few problems with your HTML I would like to mention:
Nowadays, most people use lists (<ul>, mostly) for navigation.
Having a <div> inside an <a> is invalid if the <div> has display: block (default) and the <a> has display: inline (default).
One document may only have one element per ID. You currently have several elements with the menu_part id.
Using name for anchor points is not recommended. Prefer using ID's.
All IDs must be unique. You're currently repeating menu_part. I'd suggest removing the duplicate IDs. Give the nav links a class of "nav_link" and then use jquery to reference that class with an onclick event that changes the class to "menu_choosed".
Try this:
$(document).ready(
function()
{
var currentPage = window.location.hash;
$('#head_menu a div').each(
function()
{
if( currentPage == $(this).parent().attr("href") )
{
$(this).addClass("menu_choosed");
}
}
)
}
)
it should be $('#head_menu>a>div') I believe.
also, ids are supposed to be unique, so it could cause problems that you have multiple divs with the same id. you may want to change menu_part to a class.
You can use:
$("#head_menu").find("a[href=" + window.location.hash + "]").addClass('highlight')

Categories

Resources