Fire 2 actions with ONE click on a button - javascript

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.

Related

How to close navbar when clicking outside of it

How can I edit my code so that the navbar closes when clicked outside of it but remain open if something inside of it is clicked?
$(document).ready(function() {
$('.nav-btn').on('click', function() {
$('.nav-btn').removeClass('active');
$(this).parent().find('.sub-menu').slideToggle();
$(this).toggleClass('active');
});
});
$(document).ready(function () {
$('.nav-btn').on('click', function (e) {
// Stop Document to be clicked when clicked in nav.
e.stopPropagation()
$('.nav-btn').removeClass('active');
var subMenu = $(this).parent().find('.sub-menu')
if (!$(".sub-menu").is(":visible")) {
$(this).parent().find('.sub-menu').slideToggle();
}
$(this).toggleClass('active');
});
// Toggle Sub Menu and remove active when Any vacant place is clicked
$(this).on('click', function (event) {
$('.nav-btn').removeClass('active');
$('.nav-btn').parent().find('.sub-menu').slideToggle();
});
// Prevent View close when Sub Items is clicked
$('.sub-menu').on('click', function (e) {
e.stopPropagation()
})
});
Hi, You just need to prevent the document click when clicked on the nav item and handle some additional things as done in the above code.
You can see Plunker example here also.
$(document).on('click', function (event) {
if ($(event.target).closest('.main-nav').length === 0) {
// Close button code
}
});
Another possible way is by wrapping all the content inside another div (except the header & navbar) and using the onclick tag:
<div onclick="hideNavbar()">
all your content goes here
</div>
function hideNavbar() {
$('.navbar-collapse').collapse('hide');
// getting the navbar div with jQuery
// and calling the function 'hide' of the Bootstrap class 'collapse'
}

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');
}
});

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
}
});
});
});

Hide/Show different links

I have a script that works on one link on jsfiddle.
I have two links. Link one is "Link one" the other one is "Link two" you can see the code on jsfiddle = http://jsfiddle.net/lamberta/7qGEJ/4/
It works to show and hide but i cant make it show one and other. It shows everything.
If i press Link one I want to show ".open-container-One"
And if I press Link two i just want to show "open-container-Two"
Hope you understand my issue.
jsCode:
$(document).ready(function() {
var $div = $('.test');
var height = $div.height();
$div.hide().css({
height: 0
});
$('a').click(function() {
if ($div.is(':visible')) {
$div.animate({
height: 0
}, {
duration: 500,
complete: function() {
$div.hide();
}
});
} else {
$div.show().animate({
height: height
}, {
duration: 500
});
}
return false;
});
});​
Get the index from the clicked anchor, in this case that would have to be the wrapping li, and then use that index to select the right one in the collection of .test elements. No need to recreate the slideUp/Down already built into jQuery.
$(function() {
var elems = $('.test').hide();
$('a').click(function(e) {
e.preventDefault();
var selEl = elems.eq($(this).closest('li').index());
selEl.slideToggle(600);
elems.not(selEl).slideUp(600);
});
});​
FIDDLE
Although I like #adeneo's answer, I prefer this method using selectors rather than elements :
$(".test").hide();
$('.list a').each(function(i) {
$(this).on("click", function() {
$(".test").slideUp(0).eq(i).slideDown(400, function() {
$(".close a").on("click", function() {
$(".test").slideUp();
}); // on click close
}); // after slideDown (shown div)
}); // on click link
}); // each
The only condition is that there should be the same number of links (list items) as the number of div to be shown and in the same order.
See JSFIDDLE
Give class to the anchor tag,
Link 01
Link 02
give the appropriate class as id to the div tag as
<div id="link1" class="test">
...
...
</div>
<div id="link2" class="test">
...
...
</div>
Do the below change in your javascript function
$('a').click(function() {
$('div.test').hide();
var showDivClass = $(this).attr("class");
$("#" + showDivClass).show().animate({
height: height
}, {
duration: 500
});
$('div.test').not("#" + showDivClass).hide().animate({
height: 0
}, {
duration: 500
});
});
Update and test.
Please provide the id to anchor tag which will be same as the class you need to show/hide.
and replace the $div with the id tag

How to pass specific list element to Javascript function

On my web page, I have a list of images. Currently, when the user hovers their mouse over any image for 3 seconds, a showUpdateImageDialog() method executes which causes a jQuery dialog to pop up. If the user moves their mouse away from the image at any point during the 3 seconds, the timer is reset and the jQuery dialog never displays:
HTML:
<ul class="imageGroup">
<li class="imageLi">
<img class="image" src="fizz/buzz/blah.jpg"/>
</li>
<li class="imageLi">
<img class="image" src="fizz/buzz/example.jpg"/>
</li>
...
</ul>
<div id="edit-image-description-frame" title="Update Image Description">
<div id="thumbnail-dialog-image-container">
<!-- How do I get the 'src' attribute to be the correct image file? -->
<img src="???"/>
</div>
</div>
JS:
$(".imageLi").live({
mouseenter:
function()
{
window.myTimeout = setTimeout(showUpdateImageDialog,3000);
},
mouseleave:
function()
{
clearTimeout(window.myTimeout);
}
});
function showUpdateImageDialog()
{
$('#edit-image-description-frame').dialog({
modal:true,
minHeight:500,
minWidhth:500
});
}
Unfortunately, this code behaves the same regardless of which image in the list the user is hovering over. I need a way for the jQuery dialog to display the specific image that the user is hovering over:
How can I pass the image's source to jQuery so that I can have the dialog present this image back to the user? This may seem strange, but the dialog will allow the user to edit metadata about the image and update that metadata. Because of other constraints, I need to use the image's src attribute to look up the metadata. Thanks in advance!
$(".imageLi").live({
mouseenter: function()
{
var src = $(this).children('img')[0].src;
window.myTimeout = setTimeout(function ()
{
showUpdateImageDialog(src);
},3000);
},
mouseleave: function()
{
clearTimeout(window.myTimeout);
}
});
function showUpdateImageDialog(src)
{
$('#thumbnail-dialog-image-container').children('img')[0].src = src;
$('#edit-image-description-frame').dialog({
modal:true,
minHeight:500,
minWidth:500
});
}
Pass it as a parameter to your function
$(".imageLi").live({
mouseenter:
function()
{
var element = $(this).find('img');
window.myTimeout = setTimeout(function(){showUpdateImageDialog(element);},3000);
},
mouseleave:
function()
{
clearTimeout(window.myTimeout);
}
});
function showUpdateImageDialog(image)
{
// do what you want with image variable
// it refers to the img element inside the li that was hovered
$('#edit-image-description-frame').dialog({
modal:true,
minHeight:500,
minWidhth:500
});
}

Categories

Resources