javascript/jquery shorthand code and active function - javascript

I have this code i would like to know if there is a shorter way of writing it?
also which code do i need to make an active tab stay active when on the relevant div
thanks
$(document).ready(function () {
$(".overveiw").click(function () {
$(".div1").show();
$(".div2").hide();
$(".div3").hide();
$(".div4").hide();
$(".div5").hide();
});
$(".tour").click(function () {
$(".div2").show();
$(".div1").hide();
$(".div3").hide();
$(".div4").hide();
$(".div5").hide();
});
$(".websites").click(function () {
$(".div3").show();
$(".div1").hide();
$(".div2").hide();
$(".div4").hide();
$(".div5").hide();
});
$(".faq").click(function () {
$(".div4").show();
$(".div1").hide();
$(".div3").hide();
$(".div2").hide();
$(".div5").hide();
});
$(".support").click(function () {
$(".div5").show();
$(".div1").hide();
$(".div3").hide();
$(".div4").hide();
$(".div2").hide();
});
});

It looks like what you're trying to do is show one div and hide a bunch of others when other elements are clicked — e.g., a tabbed interface.
The easy way is to use something someone's already built for you, like jQuery UI's tabs.
But you can also easily relate the divs to show/hide (the panels) and the divs that you click on (the tabs) by giving them some information in common. For instance, if you put an attribute on the panels that identifies the tab they belong to, this gets a lot shorter:
$(".overview, .tour, .websites, .faq").click(function() {
var thisTab = $(this).attr("data-panel");
var container = $("#container");
container.find("div").hide();
container.find("div[data-panel=" + thisTab + "]").show();
});
...works if you put a data-panel attribute on both the tab and panel that agrees. Live example
But if you run that live example without JavaScript, notice how it doesn't degrade well. That's why you normally see this done with lists and anchors for navigation, e.g., like this:
<ul id='tabs'>
<li class="overview">Overview</li>
<li class="tour">Tour</li>
<li class="websites">Websites</li>
<li class="faq">FAQ</li>
</div>
<div id='container'>
<div id="overview">The overview panel</div>
<div id="tour">The tour panel</div>
<div id="websites">The websites panel</div>
<div id="faq">The FAQ panel</div>
</div>
With this code:
$("#container div:not(#overview)").hide();
$("#tabs > li > a").click(function() {
var thisTab = this.href;
var index = thisTab.indexOf("#");
if (index >= 0) {
thisTab = thisTab.substring(index + 1);
}
$("#container div").hide();
$("#" + thisTab).show();
return false;
});
Live example

Give each of those divs another class:
<div class="div1 new_class"></div>
Then:
$(".overveiw").click(function () {
$(".new_class").hide();
$(".div1").show();
});

Related

jquery click to close current div using attr id

I have one problem with jquery secon click to close opened div.
I have created this DEMO from codepen.io
In this demo you can see there are two button div with blue color.So before clicked first button after click second button the first <div class="emoWrap" id="ac1"> is not closing.
I tryed the following js code:
$(document).ready(function() {
$("body").on("click", ".button", function(e) {
e.stopPropagation();
var ID = $(this).attr("id");
$("#ac" + ID).toggleClass("emoWrap-active");
/*var $current = $(this).find('.emoWrap').toggleClass("emoWrap-active");
$('.emoWrap').not($current).removeClass('emoWrap-active');*/
});
$("body").click(function(){
$(".emoWrap").removeClass("emoWrap-active");
});
});
HTML
<div class="container">
<div class="button" id="1">1</div>
<div class="emoWrap" id="ac1">
<div class="Emojis">For 1</div>
</div>
</div>
<div class="container">
<div class="button" id="2">2</div>
<div class="emoWrap" id="ac2">
<div class="Emojis">For 2</div>
</div>
</div>
Try this codepen example, I edited it so that all other emoWraps will turn off when a different one is clicked. This also means that it is exapandable, just change the IDAmount to the number of emoWraps you have.
This is the edited JavaScript code:
var IDAmount = 2;
$(document).ready(function() {
$(".button").on("click", function(e) {
e.stopPropagation();
var ID = $(this).attr("id");
$("#ac" + ID).toggleClass("emoWrap-active");
for(var i = IDAmount; i >= 1; i--){
if(i != ID){
$("#ac" + i).removeClass("emoWrap-active");
}
}
});
});
Just add a bit more logic to your first function. This isn't how I'd do it, but building on your code would be something like:
$(".button").on("click", function(e) {
e.stopPropagation();
var ID = $(this).attr("id");
if($("#ac" + ID).hasClass('emoWrap-active')) {
$(".emoWrap").removeClass("emoWrap-active");
} else {
$(".emoWrap").removeClass("emoWrap-active");
$("#ac" + ID).toggleClass("emoWrap-active");
}
});
Like so: http://codepen.io/anon/pen/wMqZqY
Sorry, didn't test. Although you do not need both clicks. You can remove from all the classes then just add the one you want:
e.stopPropagation();
var ID = $(this).attr("id");
$(".emoWrap").removeClass("emoWrap-active"); // Add this
$("#ac" + ID).addClass("emoWrap-active");

Hide content when clicking outside div with jquery

I'm using jquery to togle content with a button, I would like to hide the content when I click outside my "contentcone" div. The HTML is the following
<div class="togglecone">
</div>
<div class="contentcone">
<div class="contentleft">
<div class="title">
Cone
</div>
<div class="maincopy">
Hello my friends this is a really nice cone that can be placed anywhere
</div>
<a href="https://www.mcnicholas.co.uk/" class="button">
View on website
</a>
</div>
<div class="contentright"> <img src="images/cone.png" alt=""/>
</div>
</div>
This is the script
$(document).ready(function(){
var $content = $(".contentcone").hide();
$(".togglecone").on("click", function(e){
$(this).toggleClass("expandedcone");
$content.slideToggle();
});
});
http://jsfiddle.net/thomastalavera/SCKhf/914/
This should do it:
$(document).ready(function(){
var $content = $(".contentcone").hide();
$(document).on("click", function(e) {
if( $(e.target).is(".togglecone") ) {
$(this).toggleClass("expandedcone");
$content.slideToggle();
} else {
$content.slideUp();
}
});
});
DEMO
You need to set a click event on document to close the box. I tried to keep your original click function intact.
$(document).ready(function(){
var $content = $(".contentcone").hide();
$(".togglecone").on("click", function(e){
$(this).addClass("expandedcone");
$content.slideDown();
});
$(this).on('click', function(e) {
if ($(e.target).is('.togglecone')) { // don't slide up if you click the cone
return;
}
if ($(".togglecone").hasClass('expandedcone')) {
$content.slideUp();
$(this).removeClass("expandedcone");
}
});
});
http://jsfiddle.net/SCKhf/925/
A simple and pretty blunt way to do this is:
$(document).ready(function(){
var $content = $(".contentcone").hide();
$(".togglecone").on("click", function(e){
e.stopImmediatePropagation();
$(this).toggleClass("expandedcone");
$content.slideToggle();
});
$("body").on("click", function(e){
if ($(".contentcone").is(':visible')) {
$(".togglecone").click();
}
});
$(".contentcone").on("click", function(e){
e.stopImmediatePropagation();
return false;
})
});
But note it has a lot of disadvantages, is just a blunt solution to your problem, it must be tweaked to be ok as a permanent choice.
Edit (to answer the question in comment):
Sure, I know more than 1, each depending on your layout. You can:
a) Instead of the "body" part, make a selector for whatever elements you want to toggle event one. This works ok on layouts with a small number of big (as size on screen) elements.
b) Add one more condition to the "body" part, where you get mouse position and use it to see if the mouse is in the place you want. You can do this with e.pageX/e.pageY, or you can find relevant relative position to an element here jQuery get mouse position within an element.
This should do it with lesser code:
$(document).mousedown(function (e) {
var container = $(".togglecone");
if (!container.is(e.target) && container.has(e.target).length === 0)
{
container.fadeOut('slow');
}
});

Fire 2 actions with ONE click on a button

I'm trying to assign two actions to a button in jQuery. The button is supposed to:
open a hidden div, and...
scroll down to get said div into view.
While both actions are working on the button, they currently require 2 clicks. On the first click the div appears, but to scroll it into view I need to click the button a second time.
Any suggestions how I am going wrong?
jQuery
$(document).ready(function () {
"use strict";
$('.footer a').click(function (event) {
event.preventDefault();
$('.impr-text').hide(); // hide previous popup div
var id = $(this).data("id"); // get the div id which to show
$('#' + id).fadeIn(function () { // show cuurent click link's popup
$(this).css({
'display': 'block'
});
});
$.scrollTo( '#impressum-footer', 800, {easing:'elasout'} );
});
});
HTML
<div id="impressum-footer">
<div class="footer">
<div class="inner-wrap-imp">
<ul class="impressum-links">
<li>Impressum</li>
<li>|</li>
<li>Datenschutz</li>
<li class="impressum-button" ></li>
</ul>
</div>
</div>
<div id="impr-text" class="impr-text">
<div class="inner-wrap"> ...
You need to put the scrollTo in the fadeIn completion callback handler. That way callTo is performed on completion of the fadeIn rather than, essentially, at the same time. Currently you seem to also be placing a callback function where another parameter is to go (either duration or options object depending on which method signature you are using). Not sure why you have the css change there at all.
Try something like this:
$(document).ready(function () {
"use strict";
$('.footer a').click(function (event) {
event.preventDefault();
$('.impr-text').hide(); // hide previous popup div
var id = $(this).data("id"); // get the div id which to show
$('#' + id).fadeIn({
duration: 100, // or whatever duration you want to use
complete: function() {
$.scrollTo( '#impressum-footer', 800, {easing:'elasout'} );
}
});
});
});
if you want to assign 2 different actions on one button, set it 2 different classes (or IDs), lets say
<div class="action1 action2">
After, in jQuery you will be able to do:
$('.action1').on('click', function (e) { console.log('#1'); ... });
$('.action2').on('click', function (e) { console.log('#2'); ... });
JsFiddle: http://jsfiddle.net/g2wdd2cb/
I have now managed to get it going. The approach as explained by #euvl was the one...
I changed my code (the scrolling part) after I realized it wasn't working. The final (working) code now looks like this:
jQuery:
$(document).ready(function () {
"use strict";
$('.footer-action-1 a').click(function (event) {
event.preventDefault();
$('.impr-text').hide(); // hide previous popup div
var id = $(this).data("id"); // get the div id which to show
$('#' + id).fadeIn(function () { // show cuurent click link's popup
$(this).css({
'display': 'block'
});
});
});
});
$(document).on('click','.footer-action-2 a', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
HTML:
<div id="impressum-footer">
<div class="footer footer-action-1 footer-action-2">
<div class="inner-wrap-imp">
<ul class="impressum-links">
<li>Impressum</li>
<li>|</li>
<li>Datenschutz</li>
<li class="impressum-button" ></li>
</ul>
</div>
</div>
<div id="impr-text" class="impr-text">
<div class="inner-wrap">
The only problem now is that it scrolls a little too far. The moment I add an offset it stops working.

Nav/Subnav list, how to give clicked item active class after reload of page

I have a couple nested & hidden sub-nav lists
<ul class="nav">
<li>Home</li>
<li><a class="profile" href="#">Profile</a>
<ul id="profile">
<li>Company</li>
<li>Structure</li>
<li>Team</li>
</ul>
</li>
<li><a class="projects" href="#">Projects</a>
<ul id="projects">
<li>Chapter</li>
<li>Pblc Trde</li>
<li>Globe</li>
<li>Komforte</li>
</ul>
</li>
I am currently using some jQuery i found online to show/hide the sub-nav upon click. What I am trying to accomplish is:
Hopefully clean up the show/hide click function of the sub-nab menus.
When clicking on the sub-nav menu items, the corresponding page that opens, needs to have the sub-nav expanded and give the corresponding menu item active class, so as to let the user know which page they are on.
I am hoping to do this purely in JS/jQuery. The installation of the site will be in WordPress.
$(document).ready(function () {
$(".profile").click(function () {
var X = $(this).attr('id');
if (X == 1) {
$("#profile").hide();
$(this).attr('id', '0');
} else {
$("#profile").show();
$(this).attr('id', '1');
}
});
//Mouse click on nav
$("#profile").mouseup(function () {});
//Document Click
$(document).mouseup(function () {
$("#profile").hide();
$(".profile").attr('id', '');
});
$(".projects").click(function () {
var X = $(this).attr('id');
if (X == 1) {
$("#projects").hide();
$(this).attr('id', '0');
} else {
$("#projects").show();
$(this).attr('id', '1');
}
});
//Mouse click on nav
$("#projects").mouseup(function () {});
//Document Click
$(document).mouseup(function () {
$("#projects").hide();
$(".projects").attr('id', '');
});
});
window.onload = function () {
$("ul#profile li:first").addClass("active");
};
$(document).ready(function () {
$("ul#profile").show()
});
$(document).ready(function()
{
// Get the name of the page. Split the URL at the '/':s and get the last part
// with pop():
var pageName = (location.pathname).split('/').pop();
// If we couldn't get a page name, default to index.html:
if( pageName == '' )
{
pageName = 'index.html';
}
// Hide ul:s that are children of the navigation:
$('.nav ul').hide();
// Event handler for clicks on navigation links:
$('.nav a').on('click', function()
{
// Change visibility for the first ul-child of the current li.
// $(this) refers to the clicked element.
$(this).parent('li').find('ul').first().toggle();
// Hide other sub-menus:
$(this).parents('li').siblings('li').children('ul').hide();
});
// Search through all link elements in the nav menu:
$('.nav').find('a').each(function(index, value)
{
// Append a '$' to the pagename to make the match()-function search
// from the end of the href value:
pageName += '$';
if( value.href.match(pageName))
{
// If the pagename matches the href-attribute, then add the 'active'
// class to the parent li, and show parent ul:s:
$(this).parent('li').addClass('active').parents('ul').show();
}
});
});
You could use a Cookie to hold the value of the currently open menu. This will allow for the value to be saved/retrieved between page loads and browser sessions.
As you've already got jQuery setup you can use the jQuery Cookie plugin to simplify things.
The code for it is quite simple (more examples on plugin page).
$.cookie('open_menu', 'projects'); //Save 'projects' under 'open_menu'
$.cookie('open_menu') //Returns 'projects'
Just check the value on page load and save it when one of the menu's is clicked.
If you'd prefer not to add any extra plugins here's some documentation on JavaScript's inbuilt cookie API.
Edit: I've created a JSFiddle with an example for you. The Cookie code doesn't seem to work in there sandbox, but the code should work for you, let me know if you have any troubles.
$(window).load(function() {
if ($.cookie('show_menu') !== undefined) {
$('#' + $.cookie('show_menu')).click();
}
$('.nav > li > ul').each(function () {
//Hide the sub lists
$(this).hide();
//Get link with same ID as Class
var id = $(this).attr('id');
//When link is clicked
$('.' + id).click(function () {
//Get the sub list
var list = $('#' + $(this).attr('class'));
//Check if it's currently visible
if (list.is(':visible')) {
list.hide(); //Hide list
$.cookie('show_menu', ''); //Unset open menu
} else {
$('.nav > li > ul').hide(); //Hide all other lists
list.show(); //Show list
$.cookie('show_menu', list.attr('class')); //Set open menu
}
});
});
});

jquery toggle with a master switch

I am trying to use jquery toggling to show and hide features of a specific product. I have it working, however it's not perfect and wondered if anyone could help please?
Basically what I'm having problems with is that when you use the master open all and then close all of the individual items on their own, I need the master switch to revert back to show all text.
In addition I want to have a + and - icon on each of the items but can't figure out how to only replace the clicked image and not all of them in the list!
Any help would be greatly appreciated, thanks.
Script
$(document).ready(function() {
$('.toggle').hide();
$('.toggler').click(function() {
var target = this.id + '_content';
var imgtarget = this.id + '_expand';
$('#' + target).slideToggle();
$('.toggleall').text('Hide all');
$('<img src="images/collapse.gif">').prependTo('.toggleall');
});
$('.toggleall').click(function() {
if ($('.toggle').is(':visible')) {
$('.toggle').slideUp();
$('.toggleall').text('Show all');
$('<img src="images/expand.gif">').prependTo('.toggleall');
} else {
$('.toggle').slideDown();
$('.toggleall').text('Hide all');
$('<img src="images/collapse.gif">').prependTo('.toggleall');
}
});
});
Html
<div class="toggleall"><img src="images/expand.gif">Show all</div>
<br><br>
<div class="toggler" id="toggle1"><img src="images/expand.gif" class="toggle1_expand">Toggle 1</div>
<div class="toggle" id="toggle1_content">only toggle1</div>
<div class="toggler" id="toggle2"><img src="images/expand.gif" class="toggle2_expand">Toggle 2</div>
<div class="toggle" id="toggle2_content">only toggle2</div>
<div class="toggler" id="toggle3"><img src="images/expand.gif" class="toggle3_expand">Toggle 3</div>
<div class="toggle" id="toggle3_content">only toggle3</div>
Here is the jfiddle of the code (thanks François Wahl): jsfiddle.net/GUYfG
Here is the working version in a proper format :-
$(document).ready(function() {
$('.toggle').hide();
$('.toggler').click( function() {
var target = this.id + '_content';
var imgtarget = this.id + '_expand';
$('#' + target).slideToggle(function(){
if( $('.toggle').is(':visible') ) {
$('.toggleall').text('Hide all');
$('<img src="images/collapse.gif">').prependTo('.toggleall');
} else {
$('.toggleall').text('Show all');
$('<img src="images/expand.gif">').prependTo('.toggleall');
}
});
if( $('.toggle').is(':visible') ) {
$('.toggleall').text('Hide all');
}
});
$('.toggleall').click(function() {
if ($('.toggle').is(':visible')) {
$('.toggle').slideUp();
$('.toggleall').text('Show all');
$('<img src="images/expand.gif">').prependTo('.toggleall');
} else {
$('.toggle').slideDown();
$('.toggleall').text('Hide all');
$('<img src="images/collapse.gif">').prependTo('.toggleall');
}
});
});
EDIT:
Here is the fiddle
I have edited the code check now. Also check the fiddle.
To expand-collapse you can toggle a class with different background images inside a DIV, or use unordered lists (UL / LI).

Categories

Resources