Conflict with JS - targets first expander and not the one clicked. - javascript

I have a link that expands to reveal a div when clicked - however, if I have more than one on a page, if I click for eg. the third, it'll open the top one. How do I target the one clicked rather than the first/highest on the page.
$("body").on("click", ".show-hidden", function() {
var $link = $(this);
var $slidingElement = $($link.attr("href"));
if( !$slidingElement.is(':animated') ) {
$link.toggleClass("shown");
$slidingElement.slideToggle( 700 );
}
return false;

JSFiddle: http://jsfiddle.net/TrueBlueAussie/j4wDL/1/
This one works. Can you explain how your layout differs from the mockup I have provided?
$(document).on("click", ".show-hidden", function () {
var $link = $(this);
var $slidingElement = $($link.attr("href"));
if (!$slidingElement.is(':animated')) {
$link.toggleClass("shown");
$slidingElement.slideToggle(700);
}
return false;
});
The most likely cause is incorrect hrefs as they would need to include a valid JQuery selector (e.g. href="#one")

Related

Anchor link to content inside hidden div

I'm trying to link to content from an external page, using
<a name="anchor"></a>
and
The content where the anchor is located is hidden inside a drawer, using jQuery:
$(".toggle_container").hide();
See fiddle: http://jsfiddle.net/bd1mbu5j/1/
I've tried wrapping my head around the method found here, but I know there's something I'm missing.
window.onload = function() {
var hash = window.location.hash; // would be "#div1" or something
if(hash != "") {
var id = hash.substr(1); // get rid of #
document.getElementById(id).style.display = 'block';
}
};
Also should be noted, I'm not just trying to open the drawer, but link to specific content within certain drawers.
See this fiddle http://jsfiddle.net/bd1mbu5j/2/
$(".toggle_container").hide();
$("h3.trigger").click(function(){
var _this = this;
$(this).toggleClass("active").next().slideToggle("normal", function () {
var anchor = $(_this).data('anchor');
console.log(anchor);
if (anchor && $('#'+anchor).length) {
console.log($('#'+anchor).offset().top);
$('html, body').animate({scrollTop: $('#'+anchor).offset().top+'px'});
}
});
return false; //Prevent the browser jump to the link anchor
});
I added the target element id as a data attribute and picked that up once the slide toggle was finished. Then I animated down to that element if it exists.

modal popup displays different text depending on input

So I am attempting to have a modal popup that displays two messages depending on what the user types into the text box. I want the script to check whether the input contains one of two strings, either ME, or TN (as I am looking at doing a postcode checker).
no matter what i try I can't get the popup to display two messages depending on the input. I don't want the form to submit, I just want to grab the contents of what has been typed.
Here's a link to what I have so far (imagine the close icon is in the top right)..
$(document).ready(function () {
var formResult = $('#postcode-form')
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
http://www.muchmorecreative.co.uk/modal_test/basic-modal-testing-jquery-conditions/
try this:
$(document).ready(function() {
var formResult = $('#postcode-form')
var postcodeMe= /^[me]+$/;
$( "#postcode-form" ).click(function(e) {
e.preventDefault();
if ($(this).val().contains(postcodeMe)){
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
The problem is you're setting formResult as a 'global' variable (sorta). It gets its value when the page loads and never changes. You should change your code to get the value when you actually need it, not immediately after page load.
$(document).ready(function () {
var postcodeMe = /^[me]+$/;
$("#postcode-form").click(function () {
//move it to here so that you get the value INSIDE the click event
var formResult = $('#postcode-form')
if (formResult.val().indexOf(postcodeMe)) {
$("#basic-modal-content").html("<h2>Yes it works</h2>")
} else {
$("#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
A few other minor things to consider:
indexOf returns a number. You should probably do indexOf(postcodeMe) >= 0
You can look at index of HERE
Have tried these two but not happening, played around with it and found a solution..
$(document).ready(function() {
var formResult = $('#postcode-input')
$( "#postcode-button" ).click(function(e) {
e.preventDefault();
if ($('#postcode-input').val().indexOf("ME")!==-1 || $('#postcode- input').val().indexOf("me")!==-1 ){
// perform some task
$( "#basic-modal-content").html("<h2>Yes it works</h2>")
}
else {
$( "#basic-modal-content").html("<h2>no its wrong</h2>")
}
});
});
Thanks for the help though!

jQuery animation skipped when clicking quickly

Please take a look at this jsfiddle
If you click on the divs on the top quickly enough, you'll find that eventually two divs end up appearing. I've had this problem with jQuery before as well. I just ended up disabling the buttons (or animation triggers) in that case, but I'm wondering if there is a more elegant solution to this.
Here is my jQuery code -
$(function () {
var _animDuration = 400;
$("#tabLists a").click(function () {
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function () {
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function () {
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
})
});
return false;
});
});
I'm using callbacks everywhere. I would like a solution that would queue up the animation rather than, not allow me to click
try this code with a check var:
$(function(){
var check = 1;
var _animDuration = 400;
$("#tabLists a").click(function(){
if(check == 1){
check = 0;
var attrHref = $(this).attr('href');
// Get shown anchor and remove that class -
$('.shownAnchor').removeClass('shownAnchor');
$(this).addClass('shownAnchor');
// first hide currently shown div,
$('.shownDiv').fadeOut(_animDuration, function(){
debugger;
// then remove the shownDiv class, show the clicked div.
$(this).removeClass('shownDiv');
$('#' + attrHref).fadeIn(_animDuration, function(){
// then add that shownDiv class to the div currently being shown.
$(this).addClass('shownDiv');
check = 1;
})
});
}
return false;
});
});
DEMO

Detecting href click

Ok, so I have been trying for a few days now to figure out how to detect a user click, and assign new properties to a variable. I have attempted this in a few different ways most of them however not working.
So far I have this, which is pretty self explainitory.
var settings = {
objSlideTrigger: '#one', // link button id
objSlidePanel: '#content-one' // slide div class or id
};
if(document.getElementById('#one').click) {
var setup = settings;
setup.objSlideTrigger = '#one',
setup.objSlidePanel = '#content-one'
};
if(document.getElementById('#two').click) {
var setup = settings;
setup.objSlideTrigger = '#two',
setup.objSlidePanel = '#content-two'
};
when the user clicks a href on the page it I want it to be detected by the javascript and, for the correct setup to be placed within the settings var for use by the rest of the code.
I have two questions really the first being, I will have to duplicate the conditional statement at least ten times so is there anyway to condense/simplify the code.
secondly,When detecting a Href click in javascript do i have to assign an onclick value to the actual element in the html?
thanks again.
With jQuery
Assuming you're wanting to use jQuery because you've included it at the top, use:
$(document).on('click', '#one', function( event ) {
//Do Code here
//For #one click event
});
Although, to prevent DRY - keep it more generic by using Classes:
<div class="updatesettings" id="one">One</a>
<div class="updatesettings" id="two">Two</a>
<script>
$(document).on('click', '.updatesettings', function( event ) {
//Do Code here
//For all .updatesettings click event
alert( $(this).attr('id') );
});
</script>
With JavaScript
var OnOneClick = function() {
// Your click handler
};
var OneClick = document.getElementsById("#one");
OneClick.addEventListener('click', OnOneClick, false);
Then to listen for multiple, use by Class (Although not all IE versions can listen for this):
var AwaitedClickEvent = function() {
//Class Click
}
var WaitingClick = document.getElementsByClassName('clickme');
for (var i = 0; i < WaitingClick.length; i++) {
var current = WaitingClick[i];
current.addEventListener('click', AwaitedClickEvent, false);
}
Your Solution
<!-- Links with ID & Content -->
<div class="updatesettings" id="one" data-content="content-one">One</a>
<div class="updatesettings" id="two" data-content="content-two">Two</a>
<script>
/**
* Get the clicked element's ID
* and it's stored data-content string.
**/
$('.updatesettings').on('click', function( event ) {
var Id = $(this).attr('id'),
Content = $(this).data('content'),
setup = settings,
setup.objSlideTrigger = Id,
setup.objSlidePenl = Content;
console.log( setup );
});
</script>

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.
The problem most likely lies somewhere within the click event. Here is the code:
$('#tab-list li a').click(
function() {
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:
if ($(':animated')) {
// Don't do anything
}
else {
// Do transition
}
But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.
If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating).
On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes.
var blockAnimation = false;
$('#tab-list li a').click(
function() {
if(blockAnimation != true){
blockAnimation = true;
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow', function(){ blockAnimation=false; });
}
);
}
}
return false;
}
);
Well this is how i did it, and it worked fine.
$(document).ready(function() {
$(".clickitey").click(function () {
if($("#mdpane:animated").length == 0) {
$("#mdpane").slideToggle("slow");
$(".jcrtarrow").toggleClass("arrow-open");
}
});
});
this is not doing what your code does ofcourse this is a code from my site, but i just like to point how i ignored the clicks that were happening during the animation. Please let me know if this is inefficient in anyway. Thank you.
I toyed around with the code earlier and came up with the following modification which seems to work:
$('#tab-list li a').click(
function() {
$('.tab:animated').stop(true, true);
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
All that happens is, when a new tab is clicked, it immediately brings the current animation to the end and then begins the new transition.
one way would be this:
$('#tab-list ul li').one( 'click', loadPage );
var loadPage = function(event) {
var $this = $(this);
$global_just_clicked = $this;
var urlToLoad = $this.attr('href');
$('#content-area').load( urlToLoad, pageLoaded );
}
$global_just_clicked = null;
var pageLoaded() {
$global_just_clicked.one( 'click', loadPage );
}
As you can see, this method is fraught with shortcomings: what happens when another tab is clicked before the current page loads? What if the request is denied? what if its a full moon?
The answer is: this method is just a rudimentary demonstration. A proper implementation would:
not contain the global variable $global_just_clicked
not rely on .load(). Would use .ajax(), and handle request cancellation, clicking of other tabs etc.
NOTE: In most cases you need not take this round-about approach. I'm sure you can remedy you code in such a way that multiple clicks to the same tab would not affect the end result.
jrh.
One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});

Categories

Resources