I have a html file with many div. Beside this I have a JQuery file too which run an AJAX request in every 30 seconds. In my JQuery If a condition met and the jQuery reloded 3 times I want to update my div-s. I tried to add a div, but it does not appear just when I reload my whole page. If I set to remove my div and not add, the JQuery removes my div, so it is very odd for me, because just the .add or .append or .html do not working. furthermore I set a class with invisibility too, and I also set that when the condition met the jQuery file remove the invisibility class, but the div do not want to appear. I am trying to create a sample code.
My html
<div class="row">
<div id="myclass" class= "invisible" >
<div <p> Please appear for me!<p></div>
</div>
</div>
My JQuery:
if (condition) {
$('#myclass').removeClass('invisible');
if (n >= 2) {
$('#myclass').addClass('invisible');
}
}
The main point is, If the conditions met the class not removes just When I reload my page. In the jQuery file the n is equal with the times when the AJAX reloaded with setInterval. My question is why my div not appear just when I reload my whole page? Also why remove without reload?
Thank you in advance the answers!
removeClass and addClass perfectly work. at first, you can check if you jQuery works, just try to write you script (with ".append",".html",".insertAfter") directly in browser console, else you can add some console.log in your code, when you change invisibility like:
console.log('removeClass');
$('#myclass').removeClass('invisible');
if (n >= 2) {
console.log('addClass');
$('#myclass').addClass('invisible');
}
for update some div content, you can use simple function for it. like -
call self page in get request, and replace div content.
function reloadMyDiv(selector){
var element = $(selector);
if(element.length===1){
$.get(window.location.href,{},function(response){
var new_page = $('<div></div>').append(response);
var new_element = new_page.find(selector);
if(new_element.length===1){
element.html( new_element.html() );
console.log('update');
}else{
console.log('need contains only one element, '+new_element.length+' found!');
}
});
}else{
console.log('need contains only one element, '+element.length+' found!')
}
};
and if you more _ not use your interval, is good practice for clear it.
var n = 0;
var myInterval = setInterval(function(){ myFunction() },30*1000);
function myFunction(){
n+=1;
//do, what you want to do
if(n>2){
clearInterval(myInterval);
}
}
Related
I am trying to add a load more button to my wordpress website, to load my custom post types. So far I have been able to make it load the posts.
The problem is that every time I load more posts it replaces the first batch witch the second and so on. I want it to append every consecutive batch of posts to the first batch until the are no more (max_num_pages) posts left after that the button should deactivate.
How would I go about achieving this? Suggestions and improvements will be greatly appreciated. This is what I have so far.
<div id="div1"></div>
<button class="load-more">load more</button>
var clicks = 0;
$(".load-more").click(function(){
clicks += 1;
if(clicks < 2){
$("#div1").load("http://mysite.nl/loadmore/");
} else if(clicks > 1) {
$("#div1").load("http://mysite.nl/loadmore/page/" + clicks);
}
});
Using $("#div1").load() will replace all the HTML in #div1. I'd say load your new data on a hidden element then .append() that new data to #div1.
Or
...perhaps you can save the existing #div1 HTML to a variable:
var foo = $('#div1').html();
then load your new data and afterwards .prepend() the original:
$('#div1')
.load("http://...")
.prepend(foo);
OK, there's a weird problem with a page I have.
When the page first loads, the divs I don't want to see are hidden. But seconds later, the divs are turned back on again. When I click on a link for the main page, the divs I don't want to see, are hidden, finally.
I want to write a script, like a POST event in old PowerBuilder where when everything is said and done, the divs I don't want to see, finally get hidden.
I have 1000's of lines of code and searching is painstakingly slow.
I simply need an event that makes sure that the divs I don't want to see, stay hidden.
Here's the code:
function hideChildDivs(parent) {
parent.children('div').removeClass('shown').addClass('hidden');
}
function changePage(id, pageName, title, icon) {
switch (pageName) {
case 'treeview':
hideChildDivs($("#otherPageContent"));
showOnlyActivatedPanel('none');
$('#otherPageContent').removeClass('shown').addClass('hidden'); //<!-- This is the container wrapper... see below. -->
$("#pgCoreSettingsMaintenance").removeClass('shown').addClass('hidden'); //<!-- This element needs to remain hidden when the dashboard shows -->
$("#contentDivWrapper").removeClass("hidden").addClass("shown");
$("#dash").removeClass();
$("#tree").removeClass();
$("#thres").removeClass();
$('#mainContentPane h1 > i').removeClass().addClass(icon);
$("#pgDashboard").addClass("hidden").removeClass("shown");
$('#headerTitleTree').html(title);
$("#headerTitleRow").removeClass('hidden');
$("#headerTitleRow").addClass('shown');
$("#" + id).addClass("active");
$("#dash").removeClass("active");
$("#thres").removeClass("active");
break;
case 'dashboard': //<!-- this is the first div that is displayed on startup -->
hideChildDivs($("#otherPageContent"));
showOnlyActivatedPanel('none');
preLoader = false;
$("#contentDivWrapper").removeClass("shown").addClass("hidden");
$('#headerTitleTree').html(title);
$("#headerTitleRow").removeClass('hidden');
$("#headerTitleRow").addClass('shown');
$("#dash").removeClass();
$("#tree").removeClass();
$("#thres").removeClass();
$("#pgDashboard").addClass("shown");
$("#pgDashboard").removeClass("hidden");
$('#mainContentPane h1 > i').removeClass().addClass(icon);
$("#" + id).addClass("active");
$("#tree").removeClass("active");
$("#thres").removeClass("active");
$('#otherPageContent').removeClass('hidden').addClass('shown');
$("#pgDashboard").removeClass('hidden').addClass('shown');
$("#pgCoreSettingsMaintenance").removeClass('shown').addClass('hidden');
loadPageIntoDiv("web-resources/templates/" + pageName + ".html");
getKPIs(myUrl, myCallback);
break;
case 'threshold':
hideChildDivs($("#otherPageContent"));
showOnlyActivatedPanel('none');
$('#mainContentPane h1 > i').removeClass().addClass(icon);
$("#contentDivWrapper").removeClass("shown").addClass("hidden");
$('#headerTitleTree').html(title);
$("#headerTitleRow").removeClass('hidden');
$("#headerTitleRow").addClass('shown');
$("#" + id).addClass("active");
$("#tree").removeClass("active");
$("#dash").removeClass("active");
$("#pgDashboard").removeClass("shown").addClass("hidden");
$('#otherPageContent').removeClass('hidden').addClass('shown');
$("#pgCoreSettingsMaintenance").removeClass('hidden').addClass('shown'); //<!-- this element needs to remain hidden when the dashboard shows. -->
break;
}
}
here are the divs in order...
<div id="otherPageContent" class="hidden">
<div id="pgDashboard" class="hidden"></div>
<div id="pgThresholdConfigurationPH" class="hidden"></div>
<div id="pgCoreSettingsMaintenancePagePH" class="hidden"></div>
</div>
Use setInterval() on body onload. It may help you to get some time interval after the page loading.
Preferably you should use setTimeout(). It will call your function once, where you can hide ur divs by giving a time interval.
Did you try using the .ready() function ?
http://api.jquery.com/ready/
$( document ).ready(function() {
changePage('','dashboard','','');
});
It also seems to me that if you need to have a timer waiting for your javascript to finish running in order to set your html back to how you want it, then the order in which your code runs on start isn't right. maybe have a rethink and re-order so that after the initial load your html elements are in the correct state.
Why not give the DIV tags a class attribute and then apply a CSS style of {display:none;}?
While I've done some Javascript coding, I consider myself a more novice, Frankenstein-type coder, basically cutting and pasting with trial and error to see if I can get something to work...just a heads up on my honest assessment of my experience level.
I've got a unique thing I'm developing for, and hoping to get some help with Javascript. Here's what I'm trying / need to do: for a webpage based kiosk presentation, I'm using one HTML webpage, but with multiple sections whose visibility toggles on/off based on a Javascript I currently have that works fine. (I don't want to / can't use regular HTML pages with links because of how it ends up running).
The only problem with the above issue is that there's no easy way to create a 'back' or 'previous page' link for an end page that may have multiple ways to get to it. It won't 'know' where the user came from.
So here's what I'd like to do: pass 2 variables through my OnClick javascript function, the DIV name that needs to toggle on/off ... AND a 2nd variable of the current visible DIV name so that the next DIV that toggles on can 'remember' what the previous (and now invisible) DIV was so that there can be an accurate 'back' button.
Here's some sample code:
Each DIV section that turns on an off is setup like this:
<div id="sectionName" class="content">
</div>
These DIVs have buttons/links that are setup like this:
These run a Javacript:
function toggleVisibility(selectedTab) {
var content = document.getElementsByClassName('content');
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
So what I'm hoping is that there is a way to do something like this:
So that when that is clicked, the next DIV that turns on could also include a Javascript generated link based on that passed variable, something like:
Previous<br>Menu
I'm aware that Javascript toggling of DIVs on and off may not allow the generation of a dynamic Javascript link like the one I'm describing above, so I'm throwing this out there for some help from other, far more experienced programmers. Ideally, I'd like to try and fit everything into what I've created so far, so I don't have to start over from scratch. Any ideas?
Please reference this sample page:
www.gs3creative.com/test/
You could use location hashes (mypage.html#mydivid) and then use history.back() to handle 'back' navigation.
To stitch up the div's showing on the correct hash value....
var oldHash = '';
// fires when the hash changes
function hash_changed() {
var hash = location.hash.replace('#', ''); // get the div ID
var div = document.getElementById(hash); // find the content div on the page
var allDivs = document.getElementByClassName('content'); // get all of the content divs
// hide all the content divs
for (var i = 0; i < allDivs.length; i++) {
var thisDiv = allDivs[i];
thisDiv.style.display = 'none';
}
// only show the right one
div.style.display = 'block';
}
// this triggers the event
setInterval(function() {
// if the hash has changed, fire the function
if (oldHash != location.hash) {
oldHash = location.hash;
hash_changed();
}
}, 100); // call every 100 ms so that there is no lag
So if you set the navigation to 'mypage.html#sectionName' it would hide all other div's of the class 'content' and then only show the div with the ID of 'sectionName'.
An easy solution for me would be to render two content pages on a HTML page and show and hide content when needed from a onlick handler via javascript in your CSS add a class:
function showDiv() {
document.getElementById("theObject").className = "visible";
}
CSS:
// Switch between the content adding the classes and removing the old class
.visible{
display:none;
}
.show{
display:block;
}
Another solution using sessions "php" via javascript to hold the variables with in statements.
<?php if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['user_is where_variable'] = "im on page div 1";
}
This could also be done through js anyways.
javascript have a conditional statement using your $_SESSION vars;
if (variable == "im on page div 1" ){
// your functions
}else if ( variable == "im on page div 1"){
// another function
}
Create your click handler to update the variables in the session.
I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log
I'm trying to make some code which finds if a div exists, and if it does then have it fade away slowly. I have this to determine whether or not the div exists
if($('#error').length != 0)
{
$('#error').hide(500);
}
And that does work but only on a refresh, I've been attempting to put it in a timer like this:
var refreshId = setInterval(function()
{
if($('#error').length != 0)
{
$('#error').hide(500);
}
}, 500);
But its not getting rid of the innerHTML! I have some code which on hover alters the innerHTML of the error div so I can fill it up, but for some reason this isn't working, any advice would help!
Thank you!
$("#error").fadeOut(500);
Update:
If you are looking to check for existence:
var msg = $("#error");
if(msg.length) {
msg.fadeOut(500);
}
If you want to empty it:
$("#error").empty();
If you just want to delay 500ms then fade out, do this:
$("#error").delay(500).fadeOut();
To also empty the element, provide a callback to .fadeOut() like this:
$("#error").delay(500).fadeOut(function() {
$(this).html('');
});
There's no need to check .length, if an element that matches the selector isn't present, nothing happens :)
The div you're trying to hide likely hasn't loaded by the time your script runs. Try this; it will defer execution until the DOM is loaded:
$(document).ready(function() {
// put your code here
});
This is a good practice when using jQuery anyway.
Reference: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()