trying to hide div with content on javascript call - javascript

I Have been trying to use this http://www.gloucesterwebdesign.com/showhidecontent/
but instead of hitting a link I want some JavaScript to call this function
like
if(input == true){
toggleLayer('id');
}
else if(input == false){
toggleLayer('id2');
}
the script call the toogleLayer function, but nothing happens, and curse
the input value is place within a other script there runs at page load up. I'm been wondering if this is the problem. anyone who like to comment on this?
-- Update --
So i was ask for more of the code,
http://pastebin.com/UD3tjz1s
The value in the localStorage is set on a other page, so you only get this page after that. this is only to show what kind of data im using
im a bit of a javaScript noob, so hope it's not to hard to read

Okay, I did a quick test and this will do it. Just replace your current function iwht this, it;s a lot cleaner and simpler. Also, document.getElementById(id) is supported in every current browser and goes back to IE6, so unless you want netscape support you don't; need all the extra code your resource provided.
function toggleLayer(id){
// get the element (this is supported in all modern browsers)
var element = document.getElementById(id);
// set the style display of this element to none if its set to be
// anything else than none, otherwise set it to block
element.style.display = element.style.display != "none"
? "none"
: "block";
}
I tested this and it worked.
Edit - [different thing!]
Okay, sorry I sort of misunderstood but I found a way to fix it. Heres what it comes down to: Because your javascript code is above your DIV elements, it gets executed BEFORE the DIV elements are created by the page. So javascript will look for the elements, and it will return undefined because, well, they aren't defined yet. SO you will have to either move your script to just before the ending tag, or add the following to the code (please not I also added an interval to see your function working):
window.onload = function(){
setInterval(setSize,1000);
// the rest of your functions here - the above interval is so you can see it toggling
}
// function toggleLater(){...} here
You might also want to move ToggleLayer OUTSIDE of the window.onload function, as you can't trigger it from the page otherwise (again, the function is now defined INSIDE window.onload and outside of the scope for DIV elements...).

Related

Script that works in the browser console but not when in the code

I have a very simple piece of javascript code that just should work and it only works when I run it in the browser console:
<script>
$(".hopscotch-close").click(function () {
alert("Hi");
Cookies.set("tourState", "closed")
})
</script>
Because it runs in the console I know that:
1) the ".hopscotch-close" is OK;
2) there are no errors in the code that could prevent it from running;
Also:
1) because is a "click" event I know that I haven't got a problem with the DOM being ready (and I can put everywhere - but in this case in at the bottom of the <body>;
2) I know I don't have an issue because of using the same name for a class than something else that exist;
3) The behavior is the same in Safari and Firefox, so its not a Browser issue.
I know this is tough without the full code, but if someone has experienced this maybe has na idea about what could be the problem.
From your comments I sense that the element is getting appended dynamically so instead of
$(".hopscotch-close").on('click',
you need to make use of event-delegation as
$(document).on('click','.hopscotch-close',function(){
That will do the trick.
If you are appending .hopscotch-close to any already existing static
element then instead of $(document).on('click' you can use
$('#yourStaticElementId').on('click','.hopscotch-close',function(){
which improves site performance.

shadowbox stops working after jquery function call

I have a shadowbox script. When I load the page everything works fine, but when I call this jquery load function and then try to trigger the shadowbox by clicking on the image, the large image opens in new window instead.
Here's the code:
<link href="CSS/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="shadowbox-3.0.3/shadowbox.js"></script>
<script type="text/javascript">
Shadowbox.init();
</script>
<p id="compas"></p>
Any idea why this is happening?
EDIT
So, we finally get the bottom of this. 15 hours after first commenting on this issue, and at least 50 iterations later, we finally have identified what the problem is and how to fix it.
It actually struck me suddenly when I was creating local aaa.html and bbb.html on my server. That was when it hit me that the element nodes for the content that was being replaced was being removed altogether from the DOM when $.load() runs the callback function. So, once the #menu-home content elements were replaced, they were removed from the DOM and no longer had Shadowbox applied to them.
Once I figured this out, it was just a matter of a single web search and I found:
Nabble-Shadowbox - Reinit Shadowbox
Specifically, the response from mjijackson. What he describes is how to "restart" (reinitialize) Shadowbox using:
Shadowbox.clearCache();
Shadowbox.setup();
So once the #menu-home content was reloaded, what needs to happen is the Shadowbox cache needs to be cleared (essentially, shutting it down on the page), then the Shadowbox.setup() is run, which will detect the elements all over again. You don't run the Shadowbox.init() method again either.
I noticed that you had tried to copy/paste the Shadowbox.setup() in after the $.load(), at least sequentially in the code. However, this wasn't going to work, due to the cache clearing that needs to happen first, and primarily because the .clearCache() and .setup() functions need to be run after the $.load() completes (finishes and runs any callbacks). Those two functions need to be run in the $.load() callback handler; otherwise, you're running it's immediately, but the $.load() is asynchronous and will complete at some later time.
I'm going to go over some other changes I made, just so you understand what, why and wherefore.
Note, I'm not sure if you're familiar with <base>, but the following is at the top of the HEAD element:
<base href="http://62.162.170.125/"/>
This just let's me use the resource files on your computer. You'll not want to use this on your actual site more than likely. If you copy/paste, make sure and remove this line.
<div id="menu">
<ul>
<li><a id="menu-home" href="index.html" rel="http://jfcoder.com/test/homecontent.html">Home</a></li>
<li><a id="menu-services" href="services.html" rel="http://jfcoder.com/test/servicescontent.html">Services</a></li>
<li><a id="menu-tour" href="tour.html" rel="http://jfcoder.com/test/tourcontent.html">Tour</a></li>
<li><a id="menulogin" href="login.html">Login</a></li>
</ul>
</div>
Here, you'll notice I have a relative url in the HREF attribute, and a link to some pages on my server. The reason for the links to my server is that I couldn't access your aaa.html and bbb.html files through AJAX due to cross-site scripting limitations. The links to my website should be removed as well.
Now, the reason I'm using the rel attribute here is that I want allow for the links by way of the href attribute to continue to work in case the JS doesn't function correctly or there's some other error. If you have separate files, one for full HTML document and another for just the fragments, this is what you'll want to do. If you can serve both the full document AND the content-only from the linked file, then you probably don't need the rel attribute, but you'll need to manage the request so the server knows how to respond (full document or just the content part).
var boxInitialize = function(){
try {
if (!Shadowbox.initialized) {
Shadowbox.init();
Shadowbox.initialized = true;
} else {
Shadowbox.clearCache();
Shadowbox.setup();
}
} catch(e) {
try {
Shadowbox.init();
} catch(e) {};
}
};
All I've done here is create a central location for the initialization/setup requests. Fairly straightforward. Note, I added the Shadowbox.initialized property so I could keep track of if the Shadowbox.init() had run, which can only be run once. However, keeping it all in one spot is a good idea if possible.
I also created a variable function which can be called either as a regular function:
boxInitialize();
Or as a function reference:
window.onload = boxInitialize; // Note, no () at the end, which execute the function
You'll probably notice I removed the $() and replaced them with jQuery() instead. This can turn into a real nightmare if you end up with an environment with multiple frameworks and libraries competing for $(), so it's best to avoid it. This actually just bit me real good the other day.
Since we have a closure scope within the .ready() callback, we can take advantage of that to save several "private" variables for ow use at different times in the scripts execution.
var $ = jQuery,
$content = jQuery("#content"), // This is "caching" the jQuery selected result
view = '',
detectcachedview = '',
$fragment,
s = Object.prototype.toString,
init;
Note the , at the end of all but the last line. See how I "imported" the $ by making it equal to the jQuery variable, which means you could actually use it in that#.
var loadCallback = function(response, status, xhr){
if (init != '' && s.call(init) == '[object Function]') {
boxInitialize();
}
if (xhr.success()
&& view != ''
&& typeof view == 'string'
&& view.length > 1) {
$fragment = $content.clone(true, true);
cacheContent(view, $fragment);
}
};
This runs when the $.load() completes the process of the AJAX request. Note, the content returned in the request has already been placed on the DOM by the time this runs. Note as well that we're storing the actual cached content in the $content.data(), which should never be removed from the page; only the content underneath it.
var cacheContent = function(key, $data){
if (typeof key == 'string'
&& key.length > 1
&& $data instanceof jQuery) {
$content.data(key, $data.html());
$content.data(detectcachedview, true);
}
};
cacheContent() is one a method you may not want; essentially, if it was already loaded on a previous request, then it will be cached and then directly retrieved instead of initiating another $.load() to get the content from the server. You may not want to do this; if so, just comment out the second if block in the menuLoadContent() function.
var setContent = function(html){
$content.empty().html(html);
if (init != '' && s.call(init) == '[object Function]') {
boxInitialize();
}
};
What this does is first empty the $content element of it's contents/elements, then add the specified string-based markup that we saved earlier by getting the $content.html(). This is what we'll re-add when possible; you can see once the different links have been clicked and loaded, reclicking to get that to redisplay is really quick. Also, if it's the same request as currently loaded, it also will skip running the code altogether.
(We use $content like because it is a reference to a variable containing a jQuery element. I am doing this because it's in a closure-scope, which means it doesn't show up in the global scope, but will be available for things like event handlers.
Look for the inline comments in the code.
var menuLoadContent = function(){
// This is where I cancel the request; we're going to show the same thing
// again, so why not just cancel?
if (view == this.id || !this.rel) {
return false;
}
// I use this in setContent() and loadCallback() functions to detect if
// the Shadowbox needs to be cleared and re-setup. This and code below
// resolve the issue you were having with the compass functionality.
init = this.id == 'menu-home' ? boxInitialize : '';
view = this.id;
detectcachedview = "__" + view;
// This is what blocks the superfluous $.load() calls for content that's
// already been cached.
if ($content.data(detectcachedview) === true) {
setContent($content.data(view));
return false;
}
// Now I have this in two different spots; there's also one up in
// loadCallback(). Why? Because I want to cache the content that
// loaded on the initial page view, so if you try to go back to
// it, you'll just pickup what was sent with the full document.
// Also note I'm cloning $content, and then get it's .html()
// in cacheContent().
$fragment = $content.clone(true, true);
cacheContent(view, $fragment);
// See how I use the loadCallback as a function reference, and omit
// the () so it's not called immediately?
$content.load(this.rel, loadCallback);
// These return false's in this function block the link from navigating
// to it's href URL.
return false;
};
Now, I select the relevant menu items differently. You don't need a separate $.click() declaration for each element; instead, I select the #menu a[rel], which will get each a element in the menu that has a rel="not empty rel attribute". Again, note how I use menuLoadContent here as a function reference.
jQuery("#menu a[rel]").click(menuLoadContent);
Then, at the very bottom, I run the boxInitialize(); to setup Shadowbox.
Let me know if you have any questions.
I think I might be getting to the bottom of this. I think the flaw is the way you're handling the $.load() of the new content when clicking a menu item, coupled with an uncaught exception I saw having to do with an iframe:
Uncaught exception: Unknown player iframe
This Nabble-Shadowbox forum thread deals with this error. I'm actually not getting that anymore, however I think it came up with I clicked on the tour menu item.
Now, what you're doing to load the content for the menu items really doesn't make any sense. You're requesting an entire HTML document, and then selecting just an element with a class="content". The only benefit I can see for doing this is that the page never reloads, but you need to take another approach to how to get and display the data that doesn't involve downloading the entire page through AJAX and then trying to get jQuery to parse out just the part you want.
I believe handling the content loading this way is the root cause of your problem, hence the $.load() toggling of menu views breaks your page in unexpected ways.
Question: Why don't you just link to the actual page and skip all the $.load() fanciness? Speed-wise, it won't make that much of an impact, if any at all. It just doesn't make sense to use AJAX like this, when you could just link them to the same content without issue.
There are two alternatives that would allow you to prevent roundtrip page reloads:
Setup your AJAX calls to only request the .content portion of the markup if you have the ?contentonly=true flag in the URL, not the entire HTML document. This is how it's traditionally done, and is usually relative simple to do if you have a scripting environment.
$(".content").load('index.html?contentonly=true');
Then your server responds only with the content view requested.
Serve all of the content views within the same HTML document, then show as appropriate:
var $content = $('.content');
$content.find('.content-view').hide();
$content.find('#services-content').show();
It doesn't look like you have a whole lot of content to provide, so the initial page load probably won't have that much of an impact with this particular approach. You might have to look into how to preload images, but that's a very well known technique with many quality scripts and tutorials out there.
Either one of these techniques could use the #! (hashbang) technique to load content, although I believe there are some issues with this for search engines. However, here is a link to a simple technique I put together some time ago:
http://jfcoder.com/test/hash.html
Also, this is just a tip, but don't refer to your "content" element with a class, ie, .content. There should only be one content-displaying element in the markup, right? There's not more than one? Use an id="content"; that's what ID attributes are for, to reference a single element. classes are meant to group elements by some characteristic they share, so above when I .hide() the inline content views (see #2), I look for all of the class="content-view" elements, which are all similar (they contain content view markup). But the $content variable should refer to $('#content');. This is descriptive of what the elements are.
This worked for us, we made a site that used vertical tabs and called in the pages with our shadowbox images using jQuery.load
Just give all of your anchor tags the class="sbox" and paste this script in the header.
<script>
Shadowbox.init({
skipSetup:true,
});
$(document).ready(function() {
Shadowbox.setup($('.sbox'));//set up links with class of sbox
$('a.sbox').live('click',function(e){
Shadowbox.open(this);
//Stops loading link
e.preventDefault();
});
});
</script>
Note: we had to put the .sbox class on all our rel="shadowbox" anchors as well as the on the anchor for the tab that called the .load
Thanks to this guy-> http://www.webmuse.co.uk/blog/shadowbox-ajax-and-other-generated-content-with-jquery-and-javascript/
Well, based on Shem's answer, this is my solution.
Every click on specific class, setup and open shadowbox with elements from same class:
jQuery('.sb-gallery a').live('click',function(e){
Shadowbox.setup(jQuery('.sb-gallery a'));
Shadowbox.open(this);
//Stops loading link
e.preventDefault();
});
Thanks to all

Does browser rendering and JavaScript execution happen simultaneously?

For example, if I have this:
$('#button').click(function() {
$.get('/question', function(data) {
$('#question').html(data);
$('#question').dialog( ... );
});
return false;
});
Will the user see the question content for a brief moment before the dialog is shown?
Note: Normally I'd just hide the #question manually, but there's actually a step in between html() and dialog() with another jQuery plugin where the content must not be 'hidden'.
Short Answer
Yes, it's possible that the user will see the question content for a brief moment before the dialog is shown.
The Fix
To guarantee you won't momentarily see the contents of #question before displaying the dialog, absolutely position #question offscreen before displaying it. After that, call the jQuery plugin that requires #question to be displayed. Finally, hide #question and restore its position.
CSS
#question
{
display: none;
}
JavaScript
$('#button').click(function() {
$.get('/question', function(data) {
var question = $('#question');
question.html(data);
var position = question.css('position');
var top = question.css('top');
var left = question.css('left');
question.css({ position: 'absolute', top: -1000, left: -1000 }).show();
//whatever you need to do with #question while it's not hidden
question.hide().css({ position: position, top: top, left: left });
question.dialog( ... );
});
return false;
});
The browser will render the DOM up until that call, at which point it will stop and parse/execute your js. This is why it's considered best practice to put all script tags at the bottom of a page (so that the browser can render enough of the DOM so your visitors aren't stuck staring at a blank white screen).
Using
$(document).ready();
can alleviate this to an extent, but if you're truly concerned with when it is added to the DOM, make sure your code is added at the very bottom of your HTML's body tag.
References:
http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5/
In your case absolute not, because you are using a framework. It works like this:
1) Script code is requested from external files as the page progressively loads. An HTML parser has to parse the script tags before there is any awareness of a script request. This code executes when called, but it is fed into the JavaScript interpreter the moment it is available to the JavaScript interpreter.
2) Script code resident directly in the page is fed into the interpreter as the HTML code is parsed by an HTML parser and a script tag is encountered. Code inside functions executes when called, with one exception. Otherwise code executes immediately upon interpretation. The one exception is when a function block is immediately followed by "()" which indicates immediate invocation.
3) Most code that executes initially executes from function calls made with the "onload" event. The onload event occurs when the static DOM is fully available from the HTML parser and when all asset requests from the initial static HTML are requested. In some edge cases with older browsers it is possible for conflicting conditions to occur that create a race condition in the page that prevents the onload event from ever firing or after an extraordinary delay.
4) You are using jQuery, so you are at a severe disadvantage with regards to speed of availability. jQuery code is JavaScript code, so it has to enter the JavaScript interpreter exactly like any other JavaScript. All the prior points from this post must be observed before any jQuery code can execute.
5) When I perform A/B testing I need code to execute as absolutely as early as possible and as fast as possible to minimize flicker on the page, so frameworks are definitely not an option. In this case I follow these steps:
5a) I find the first id attribute directly after the DOM node(s) that I need to access.
5b) I write a function to test for the availability of this node. If the node is available then the areas above it are available, so I am know I am solid. Consider the following example:
var test = function () {
var a = document.getElementById("first_node_lower_than_I_need");
if (a !== null && typeof a === "object") {
//my code here, because I know my target area is available
} else {
setTimeout(test, 100);
}
};
setTimeout(test, 100);
5c) Notice in the sample code above that I call my function with a setTimout delay to give the DOM a fighting chance. If the function executes early that is okay because I am calling it recursively with a delay to give the DOM some extra time to load. If you set your delay to 50ms or lower you are increasing execution time in IE8 and lower because of numerous unnecessary calls for the function. I recommend keeping the delay at 100ms for an ideal balance cross browser, but if you really want rapid execution in new browsers then set the first delay to 50ms, this is the one outside the function, and keep the other at 100ms.
5d) Minimize your use of innerHTML property with the above method, or be very familiar with the targeted page to know when it is okay to use innerHTML. The problem with innerHTML is that it changes the page output without reporting those changes back to the parsed DOM in memory, which normally is an irrelevant disconnect. However, in this case it is certainly relevant because of how fast and early your injected code can execute. This is a problem because other code that executes later, such as with the onload event or jQuery's ready event, will either overwrite your changes or will not be able to find their respected DOM load and simply drop their execution all together. This is particularly an important concern if you are targeted a very high level node in the DOM tree, so for your safety be very specific when selecting nodes to use innerHTML or just use DOM methods. This is a bit more complicated in that you cannot use a DOM method only solution because you cannot change text nodes with the nodeValue method cross-browser as this is not supported in IE7.
If you need to execute JavaScript code before completion of DOM parsing then do not use a JavaScript framework. Write using plain regular JavaScript code and optimize the hell out of it. Otherwise you will always have flicker and the larger of the static HTML download the longer and more noticeable that flicker will be. Additionally, jQuery code tends be far slower to execute than regular optimized JavaScript due to its reliance on CSS like selectors. If your injected jQuery code is required to perform a large task on a very large static HTML document then it is unlikely to complete execution in IE7 without timing out.
This is the reason initializing any DOM-related activity should be done/triggered from within $(document).ready() .
So if you put you $.get statement inside of doc ready, you can ensure that all the elements in the HTML have been rendered and are ready to be interacted with via JS.
$(document).ready(function () {
$.get('/question', function(data) {
$('#question').html(data);
$('#question').dialog( ... );
});
});

JavaScript changes to style being delayed

I'm running into a little problem that's driving me crazy, and I'd welcome any thoughts as to the cause. At this point I feel like I'm just going 'round in circles.
I have the following code:
function JSsortTable(phase) {
dynaLoadingDivShow();
createSortArray();
dataArr = do2DArraySort(dataArr, orderList, orderDir);
sortArrayToRs();
dynaListTable.tableControl.refreshTableViaObjects(rsDynaList, colObjs);
dynaLoadingDivHide();
}
function dynaLoadingDivShow() {
document.getElementById('dynaReportGuiWorking').style.display = 'block';
document.getElementById('dynaReportGuiWorking').style.visibility = 'visible';
}
function dynaLoadingDivHide() {
document.getElementById('dynaReportGuiWorking').style.display = 'none';
document.getElementById('dynaReportGuiWorking').style.visibility = 'hidden';
}
<div style="visibility:hidden; display:none; z-index:25;" class="tableControlHeader" id="dynaReportGuiWorking">
Working...
</div>
I call JSsortTable as an onclick event. When I run the above code as is, I never see the div in question. The JSsortTable function takes some 800-2500 ms to run so it's highly unlikely I just missed it the 10+ times I tried. If I change the style of the div to start out visible, then it will remain visible until after JSsortTable has finished running and then disappear; exactly as expected. So I figured the problem was in dynaLoadingDivShow.
Now, I tried removing dynaLoadingDivHide to see what would happen and found something completely unexpected. The div will not appear when you the JSsortTable function fires. Instead, after all the other code has been run, when JSsortTable finishes, the div becomes visible. It's alomst as though IE (version 8) is saving up all the changes to the DOM and then waiting until the end to paint them. This is, obviously, not the desired behavior.
Anyone have any thoughts on this? I'm only allowed to have IE at work so I haven't tried this on other browsers. I have enough CSS/JS knowledge to be dangerous, but am by no means an expert yet. ;)
Thanks!
You'll need to use a timeout:
function JSsortTable() {
dynaLoadingDivShow();
setTimeout(JSortTableWork);
}
function JSortTableWork()
createSortArray();
dataArr = do2DArraySort(dataArr, orderList, orderDir);
sortArrayToRs();
dynaListTable.tableControl.refreshTableViaObjects(rsDynaList, colObjs);
dynaLoadingDivHide();
}
Note that I took out the parameter phase because it's not used in the function. If you do need the parameter then you'll need to modify the timeout as
setTimeout(function(){JSortTableWork(phase);});
and also add the parameter to JSortTableWork

Javascript: var is null

I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <head>
note: I am working with a local server, so pageload in instant.
function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
This here is the corresponding HTML
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
"changed is null:
changed.onchange = changeVisibility;"
i don't get it, I seriously don't get what I'm overlooking here.
EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code:
function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
This here is the corresponding HTML:
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
Attach another File
</div>
Also, thanks for the link to JSbin, didn't know about that, looks nifty.
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
note: I am working with a local server, so pageload in instant.
that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D
The onlything I'd like to do now is remove the Javascript link from the ...
Place an id on there, and inside your function do this:
document.getElementById('addField').onclick = addFileInput;
Or, as you already have the div as the variable 'a':
a.firstChild.onclick = addFileInput;
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
mercutio is correct. If that code is executing in the HEAD, the call to "document.getElementById('click1')" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.
I think its because you are trying to modify a file element.
Browsers don't usually let you do that. If you want to show or hide them, place them inside of a div and show or hide that.
Right, I've modified things based on your collective sudgestions and it works now. Onlything bothering me is the direct reference to Javascript inside the anchor
You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.
Placing at the bottom of the page works fine, as you can see here.
Decoupling event responder from your markup is covered under the topic of "Unobtrusive JavaScript" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.

Categories

Resources