Do I have to duplicate this function? - jQuery - javascript

I'm using this function to create an transparent overlay of information over the current div for a web-based mobile app.
Background: using jQTouch, so I have separate divs, not individual pages loading new.
$(document).ready(function() {
$('.infoBtn').click(function() {
$('#overlay').toggleFade(400);
return false;
});
});
Understanding that JS will run sequentially when i click the button on the first div the function works fine. When I go to the next div if I click the same button nothing "happens" when this div is displayed, but if i go back to the first div it has actually triggered it on this page.
So I logically duplicated the function and changed the CSS selector names and it works for both.
But do I have to do this for each use? Is there a way to use the same selectors, but load the different content in each variation?

Would something like this work? I'm assuming what you want is for different buttons to call toggleFade on different overlay divs.
function makeOverlayHandler(selector) {
return function() {
$(selector).toggleFade(400);
return false;
}
}
$('button selector').click(makeOverlayHandler('#overlay1'));
$('another button selector').click(makeOverlayHandler('#overlay2'));
You could also change makeOverlayHandler's selector parameter to a jQuery object instead of a selector and call it like this: makeOverlayHandler($('#overlay1')).

This best way to do this is to make it all relative, so say you have markup like this:
<div class="container">
<div class="overlay">Overlay content</div>
<button class="infoBtn">Click to show overlay</button>
</div>
Then you can find the overlay for this button realtively, like this:
$(function() { //equivalent to $(document).ready(function() {
$('.infoBtn').click(function() {
$(this).closest('.container').find('.overlay').toggleFade(400);
return false;
});
});
You can optimize this further, e.g. .children('.overlay') if the overlay is always a direct child of container. This goes from the current button (this), finds the .container it's in using .closest() and then finds the .overlay inside of it using .find(). With this approach you have one small bit of code to handle all your bindings, much easier to maintain :)

Related

jQuery onclick load randomly working with firefox

So I have a few "boxes" with an onclick function:
<div class="box" onclick="load(1);return false;"></div>
<div class="box" onclick="load(2);return false;"></div>
The onclick functions trigger a function that reads the content of a few seperate .php files (example1.php and example2.php).
These files contain other boxes made with fieldset instead of a div.
function load(num){
$("#loadthis").load("example"+num+".php");
}
And the function above is changing the content of this div down here:
<div id="loadthis">Load my fieldset boxes</div>
So far everything works, until I click on the fieldset boxes.
The background color of the fieldset should change when I click it and the radio inside the fieldset should be selected too (because of css styling), but both of this does not happen. But I can still select the radio when clicking the radio (not the box).
I have tested it in IE and in Chrome, this code works there most of the time.
But in firefox I cannot select the fieldset box 50% of the time.
I tried to experiment with the .on( class but it gives me the same effect.
$('fieldset.type-a').children('.row').children('.box.col-4').on("click", load);
function load(){
var index = $('fieldset.type-a').children('.row').children('.box.col-4').index( this );
index+=1;
$("#loadthis").load("fs"+index+".php");
}
Okay so after some searching I found that there is already an onclick function in a different .js file that being called:
function handleStep2() {
$('.step-form-2 input[type=radio]').change(function () {
$(this).closest('fieldset').find('.box').removeClass('active');
$(this).closest('.box').addClass('active');
$(this).attr('checked', 'checked');
});
$('.step-form-2 .select-box .box').click(function () {
$(this).find('input[type=radio]').trigger('change');
});
}
I am now going to try to merge the codes and see if that gets rid of the bug with the active class not being activated on click.
SOLVED: I solved it by indeed merging both the codes to 1 click function. Thanks for all your help guys, But I still wonder if this could be done a different way?
Look into event delegation, and if you're using jQuery it's easy
look into the jQuery API for .on(
Also you want to make sure you're using unobtrusive JS, so pull that out of your HTML, put it in a .js file as an event listener and load the script after the DOM has loaded as the last thing before your closing </body> tag
It should be a delay about loading php files content.
Is it work when you click one of them even takes time?
Maybe you should ajax for loading php files. By the way you can send data to php files using GET or POST methods.
You can check this examples.
If your function is initalized in an IIFE, inline js can´t access this function.
It´s weird that you say this sometimes works..
IIFE is a wrapper function to create capsules, so the client can´t modify your script in runtime.
Looks like this:
(function(){
/* code */
}());
It would be much better to create js-events:
on('body', 'click', '.box', function(e) {
console.log(e.target); // this is the clicked list item
});
Hope it helps..

jQuery - .on('click') not working on <li>

so I've been tasked with making a website using Wordpress and on the homepage there's a slider that if you click on the buttons below, it's displays another image, simple right? Well, I've got the slider and I've got the buttons, I've added the jQuery and it doesn't want to work.
I first tried making the buttons actually buttons:
<button type="button" class="btn btn-success" id="hideshow-healthcare">Healthcare</button>
and that worked fine when I used this:
jQuery(document).ready(function() {
jQuery('#hideshow-healthcare').on('click', function() {
jQuery('#healthcare').show();
};
};
So after having it working like that, I moved on to making the buttons in to li's instead so that I could follow the design. Upon doing this, the slider no longer works. I've tried mulitple different things including adding the ID to everything in the li to see if that would work, and sadly not. I did some research and tried to change
jQuery('#hideshow-healthcare').on('click', function() {
to
jQuery('li#hideshow-healthcare').on('click', function() {
but still, no luck. I was hoping someone would be able to provide a solution to this problem.
Also, this is the li code I'm currently using:
<li><a id="hideshow-healthcare"><h5>HEALTHCARE</h5> Lighting to create a feeling of well being</a></li>
You need to add space after li element to find its descendants #hideshow-healthcare. It should be
jQuery('li #hideshow-healthcare').on('click', function() {
#hideshow-healthcare is child of li. Use descendant selector in jquery
jQuery('li a#hideshow-healthcare').on('click', function(event) {
event.preventDefault(); // prevents default action
// your code
});
Id be unique in html you just straightly write with id
jQuery('#hideshow-healthcare').on('click', function(event) {
event.preventDefault(); // prevents default action
// your code
});

Jquery open and close within a parent div

The title does not explain that well, essentially I have 8 divs the same, with the same class for css styling.
They all have hidden content, I want to be able to only expand one div at a time without using different classes or identifiers for each div and hidden content.
I have tried to display this on Jsfidle using two divs the same , however I can't even get it to fire on jsfiddle for some reason
http://jsfiddle.net/dAXJ2/8/
$(document).on('click',".servicereadmore",function() {
//var x = $(this).closest('div').attr('class')
//$('.hiddenservices').parent(x).slideDown(1000);
$('.hiddenservices').slideDown(1000);
$(this).html("Read less");
$(this).removeClass("servicereadmore");
$(this).addClass("servicereadless");
});
$(document).on('click', ".servicereadless" ,function() {
$('.hiddenservices').slideUp(1000);
$(this).html("Read more");
$(this).removeClass("servicereadless");
$(this).addClass("servicereadmore");
});
That currently works above but opens all the hidden text as stated, the comments are were I have been trying to only expand within the parent div of the button I pressed
Your clickable <a> tags should probably be buttons, since that's the role they're in. Also, your functions aren't working currently because you've added
return false;
as the first statement of each one. That prevents any of the code after that from ever running. Instead of that, either change those <a> links to <button type=button> or else add a parameter to the handlers ("e" or "event") and call
e.preventDefault();
in the handler.
To affect only the portion of the page relevant to the "Read More" links, you just need to navigate the DOM:
$(this).closest('.myinfo').find('.hiddenservices').slideDown(1000);
That means: "staring from the clicked element, climb up the DOM to find the closest element with class 'myinfo', and then from that point down find all the elements with class 'hiddenservices' and slide them down."
A couple of other problems: you'll need to start the "hiddenservices" sections off as hidden, or otherwise not visible somehow. Also, another issue with your jsfiddle was that you didn't have jQuery selected. That's something you could quickly learn just by checking the error console.
Here is a repaired jsfiddle.
You dont have to use that much of code for this purpose. USe simply like
$(document).on('click', ".servicereadmore", function (e) {
e.preventDefault();
if ($(this).parent().find('.hiddenservices').is(":visible")) {
$(this).html("Read more");
} else {
$(this).html("Read less");
}
$(this).parent().find('.hiddenservices').slideToggle(1000);
});
Instead of adding and removing the class name, you can just use slideToggle().
Demo

Change Exposed elements (jQuery Tools )

I would like to cancel an exposed element and expose another one in one onClick(). Is that possible? My code doesn't work..
Here's the js:
function tutStep1(){
jQuery('#workspace_menu').expose({
onLoad: function(event) {
jQuery('.next').fadeIn();
}
});
jQuery('.tutorial .next').click(function() {
jQuery.mask.close();
tutStep2();
});
});
function tutStep2(){
jQuery('.action_list').expose();
}
Here's the html
<span onclick="tutStep1();" >tutorial</span>
The mask just won't open again unless I click on the span.
Or is there another way by not closing the mask, and switch elements to expose?
Probably not a good idea to put a click event inside a click event. I'm not familiar with this mask plugin, but speaking in the abstract, you can clean it up by doing something like this:
$('.open').click(function() {
$('#workspace_menu').show();
});
$('.tutorial, .next').click(function() {
$('.mask').hide();
$('.action_list').show();
});
Make sure you separate multiple selectors with a comma in the case of .tutorial and .next
You have your onClick events nested inside one another.
Recode and keep them all separate.

How to perform: onClick Javascript, hide a div with transition effect

This is a question that is related to a previous question of another member which can be found here.
This is the Javascript function to hide a div (which is an answer to the other member's question):
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
The HTML is:
<div id='hideme'>
Warning: These are new products
<a href='#' class='close_notification' title='Click to Close'>
<img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" />
</a>
</div>
My followup question to this is: how can I add a cool effect of transition? The result will be the div 'hideme' would close slowly. Is there a work around for this?
Thanks so much everyone! It would be highly appreciated!
Note: I'm a noob with Javascript. 0-0
$("#"+el).fadeOut(500);//el must be the id of the element
If you're using jQuery
function hide() {
$(this).parent().fadeOut();
}
As this is triggered by an event the 'this' variable will be set to the element from which it came, as you want the parent element to vanish when it's clicked this will do the trick
EDIT: For this to work you may have to play with your HTML and how many $(this).parent().parent()... you need but this would be the best way to go about it, then you don't need to pass the ID around
EDIT 2: So .parent() selects the element containing the selected element, so in this case $(this) refers to the button that was clicked as that's where the click event came from.
So $(this).parent() refers to the container element, in this case the a element and therefore the $(this).parent().parent() refers to the div element which you want to hide.
So you could give the image a class of 'closable' then do the following
$('.closable').click(function() {
$(this).parent().parent().fadeOut();
}
This means whenever you click something with the class closable it will go up the DOM tree two elements to (with .parent().parent()) and then fade it out.
This will allow you to remove the on click event from the image, you just need to put the handler above in the jQuery document.ready function which looks like:
$(document).ready(function() {
//Click function here
});
A popular choice for this would be JQuery UI's effect method.
With this, you can write some very simple Javascript to hide your div in a stylish manner, for example:
function hide(obj) {
$(obj).effect("scale");
}
EDIT:
Here's an example jsFiddle
Use jQuery to do transition effects:
$(function(){
$("a.close_notification").click(function(e){
e.preventDefault();
// stop other animations and hide, 500 milliseconds
// you can use the function fadeOut for that too
$("#hideme").stop().hide(500);
});
});

Categories

Resources