I have replicated a toggle functionality from this site:
http://www.williamsprofessionalpainting.com/FAQ.php
Here is the updated version which renders the basic toggle function with minimum CSS:
http://jsfiddle.net/NinjaSk8ter/yXNmx/
Your code is working fine, but jsFiddle is wrapping it in a function. In other words, it ends up looking something like:
window.onload = function() {
function ToggleFAQ(Ans) {
...
}
};
The function is defined within the onload handler, so when your onclick tries to call it, it doesn't exist.
If you change the drop-down on the top-left of your fiddle to "no wrap", it all works fine. See this modified version.
On your JSFiddle - if you change the wrap method to "no wrap(head)" and it simply works.
Alternatively - you can declare the function as a global var:
ToggleFAQ = function (Ans)
{
//..
}
what renders as
jQuery(document).ready(function(){
//when defined like this - ToggleFAQ will still be visible when the
//"ready" event finishes.
ToggleFAQ = function (Ans)
{
//..
}
}
the wrap you selected puts your code in a function passed to jQuery's "dom-ready" event - and that's a closure that once is executed - all local variables are "vaporized".
Related
I have following code in my JavaScript library. My goal is to store the original onscroll function which is the first line of code snippet, and then point onscroll to a new function. However, what I am finding is that wind.origonscroll which is supposed to be the original scroll function is always pointing to the new function in second line.
Question: Is there a way to store the original function in code below, so window.origscroll always points to the function in first line of commented code? I am trying to keep track of what was the original window's onscroll event, which is not related to overriding a function. I do not need to override a function here.
//window.onscroll = function() {console.log('scrolling done');}
wind.origonscroll = window.onscroll;
window.onscroll = function () { window.scrollTo(wind.x, wind.y); };
If window.onscroll is not null ( if has been defined before) it can be saved away.
Try this:
window.onscroll=function() { console.log('asd') }
var old = window.onscroll
window.onscroll=function() { console.log('gggg') }
old()
I am trying to get this function to be called via click event, but for some reason it is being called when page loads. I am completely baffled on why my function is reacting this way.
Here is my function
var registerTab = function(panel){
var active = 'off';
if($('#'+panel).css('left') <= '0'){
$('#'+panel).animate({left: '0'});
active = 'on';
} else {
$('#'+panel).animate({left: '-380px'});
}
};
$(function() {
tabRegister.on('click', registerTab('sidePanel'));
});
The weird thing is if i call it when i remove the passed variable and hard-code the selector in it works fine which again makes no since to me. Please any help would be very helpful and save me some hair.
registerTab('sidePanel')
This call will cause the function to be called immediately. I think what you really want is this:
tabRegister.on('click', function () {
registerTab('sidePanel')
});
I have a question about a onclick's JavaScript behavior. I have two JavaScript classes that initialize a onclick function in a element, but when I apply the onclick initializers on the same html element only works the last onclick function, I don't understand this behavior. I test to get the same situation in a simple example and the results are the same. Here's my example code with this strange behavior:
window.onload = function ()
{
var testElem = document.querySelector('#test_element');
test_element.onclick = function ()
{
alert('one');
}
test_element.onclick = function ()
{
alert('two');
}
}
And here is my HTML
<div id="test_element">click here to test_element</div>
When I click on the trigger I need to throw the two alerts "one" and "two" but it seems like the second overrides the first. Please, somebody can help me to resolve this problem?
Use addEventListener, which can handle multiple handlers for the same event:
test_element.addEventListener('click', function(){
alert('one');
}, false);
test_element.addEventListener('click', function(){
alert('two');
}, false);
The onclick property (aka inline) only supports a single handler.
You're looking for addEventListener(eventName, handler), which is the correct way to add handlers in JS.
It will let you add as many handlers as you want.
I am using the following code to load two underscore.js templates. Once the first link is clicked, the skeleton template is loaded. The first trigger executes the find bind, which executes the loadBookmarks function correctly, but the 'loaded' trigger never fires and the loadFriendBookmarks never executes. Why is this? Is there another way to make this happen?
$('#bookmarks-link').click(function() {
$('#bookmarks-count').text("0");
var skeleton = modalTemplate();
$('#bookmarks').append(skeleton);
$('#bookmarks').trigger('skeleton');
});
$('#bookmarks').bind('skeleton', function() {
$('#bookmarks .thumbnails').loadBookmarks( getBookmarksUrl(1) );
// If I add an alert('hi') here, it works perfectly.
$('#bookmarks').trigger('loaded');
});
$('#bookmarks').bind('loaded', function() {
$('#bookmarks .thumbnails a').each(function() {
$(this).bind('click', function() {
$('#bookmarks .bookmarks-table tbody').empty();
$('#bookmarks .bookmarks-table tbody').loadFriendBookmarks(
getFriendBookmarksUrl($(this).attr('data-item'))
);
});
});
});
So interesting enough, the triggers do work correctly: If I stick an alert in between loadBookmarks and trigger, everything works fine. If I take it out, then it doesn't. Any idea why?
Based on your description and common sense, it sounds like loadBookmarks() loads data from a remote source, such as an ajax call. This means that trigger('loaded') can fire before loadBookmarks() has received the data. You can add a callback argument to loadBookmarks() and trigger the event there:
$('#bookmarks .thumbnails').loadBookmarks( getBookmarksUrl(1) , function() {
$('#bookmarks').trigger('loaded');
});
But this requires your loadBookmarks to know to call this function after it receives the data and creates the needed HTML - I can't demonstrate this without seeing the actual code you have in loadBookmarks.
Additional suggestion: don't bind handlers this way, use event delegation instead:
$('#bookmarks').on('click', '.thumbnails a', function(e) {
e.preventDefault(); // don't want the link to actually be followed, do we
var url = getFriendBookmarksUrl($(this).attr('data-item'));
if(url) { // in case it's clicked before the data attribute is set
var $tbody = $('#bookmarks .bookmarks-table tbody');
$tbody.empty();
$tbody.loadFriendBookmarks(url);
}
});
This means that all elements matching the selector '#bookmarks .thumbnails a' will call this click handler, even if they were added to the document after you called on. Meaning you can delegate these events even before calling loadBookmarks, removing the need for the loaded event at all. Plus, this way you only have one copy of the handler function in memory, as opposed to your bind which created a separate copy of the function for each a node.
the problem is else where in your code. probably some js error in loadBookmarks* functions.
see:
http://jsfiddle.net/BBESV/
triggers work perfectly
I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on
$('selector').click(function() {
//I would realy like this variable to be updated
var click = 0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.
Have a look at jQuery's .data() method. Consider your example:
$('selector').click(function() {
var $this = $(this),
clickNum = $this.data('clickNum');
if (!clickNum) clickNum = 1;
alert(clickNum);
$this.data('clickNum', ++clickNum);
});
See a working example here: http://jsfiddle.net/uaaft/
Use data to persist your state with the element.
In your click handler,
use
$(this).data('number_of_clicks')
to retrieve the value and
$(this).data('number_of_clicks',some_value)
to set it.
Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet
Edit: fixed link
Another alternative might be to have two functions, and bind one using the one function in $(document).ready() (or wherever you are binding your handlers), and in that function, bind the second function to be run for all subsequent clicks using bind or click.
e.g.
function FirstTime(element) {
// do stuff the first time round here
$(element.target).click(AllOtherTimes);
}
function AllOtherTimes(element) {
// do stuff all subsequent times here
}
$(function() {
$('selector').one('click', FirstTime);
});
This is super easy in vanilla Js. This is using proper, different click handlers
const onNextTimes = function(e) {
// Do this after all but first click
};
node.addEventListener("click", function onFirstTime(e) {
node.addEventListener("click", onNextTimes);
}, {once : true});
Documentation, CanIUse
If you just need sequences of fixed behaviors, you can do this:
$('selector').toggle(function(){...}, function(){...}, function(){...},...);
Event handlers in the toggle method will be called orderly.
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
this would bind click event to Corresponding Html element once and unbind it automatically after first event rendering.
Or alternatively u could the following:
$("#foo").bind('click',function(){
// Some activity
$("#foo").unbind("click");
// bind it to some other event handler.
});