How to Group IDs and call them with Jquery - javascript

Is there a way to group div IDs that are scared across multiple pages but get to be called to the same page at some point with Jquery.
I want to hide or show all the divs in a group while showing only a certain group. The reason some group gets to be included in other functions and writing all the list of this many div IDs is somehow not wise.
2nd question.
How do I program a button to reload page and then after run a function with jquery?
ok let me add some code to make sense of this reload problem.
$('#accountresult').click();
location.reload(); //Should reload page 1st and then function
$('#button').show("slow");
$("#Atresult").load("source_cxchange.html #account");
$("#result, #homeresult, #appleresult" ).empty()
});
but rather, it only runs reload and dies, someone please correct the syntax of putting two functions to successively follow one another.

My advice would be to group them using a class rather than a collection of ids. That way you can target them all at once with:
$('.someClass').hide()
As for reloading the page and running a function afterwards that gets a bit trickier can you explain what you are trying to achieve?
When you refresh the page you lose the javascript callstack so you will have to set a querystring or use cookies/local storage to persist a value. You can then use jQuery's onLoad() function to run your function only if the url parameter or cookie exists.

1) Assign some class to those ids and use $('.someclass') to refer them.
2) To reload page, you will need to call 'location.reload();'. then you can do whatever you should in $(function() {});, which is called whenever page is loaded.

Related

How to stop scroll event function when the user move to another page

I am adding the scroll event in javascript for one of my pages. The code is like this:
document.getElementById("myProject").addEventListener("scroll", myFunction);
function myFunction() {
document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";
}
So, when users start scrolling, they will see a text "These are all my projects so far".
My problem is how to stop showing this text when users move to another page.
Please help ( I am a verrrry fresh developer)
Thanks so much
A few thoughts.
Without knowing your dev environment (e.g. are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.
Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.
If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.
If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.
If the case is a switching between browser tabs, you can use two different events like below.
$(window).blur(function(e) {
// stop scroll event, when switching to another tab
document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
// start scroll event
document.getElementById("myProject").addEventListener("scroll", myFunction);
});
I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.

Can I create a PagedListPager that does not call a function

I'm trying to managed a list using ajax calls, on the 1st load everything is fine as the search button makes the ajax call which loads the 1st page of results. Problem is when I create the PagedListPager it is calling the controller function with causes the page to reset and the results to disappear.
So what I would like to do is create the PagedListPager as just buttons with no actions, and handle the clicks on those buttons using Javascript. Does anybody know a way to go about this??
I could not find a solution for this using the PagedListPager. The PagedListPager creates an unordered list, which I recreated in the view with a blank link like so:
/
This is useful, because it maintains the styles used on other PagedLists on the site.Then from javascript, override the li click event, like so:
$(document).on("click", "li", function (event)
Now I can make ajax calls from each li without the page refreshing every time.
Hope this helps some people!!
A more elegant solution is to create the list with an id
<ul id="pagingbuttons" class="pagination">
And also give ids to the li elements inside the list.
So now from javascript override the click event just of that list like this
$(document).on('click', '#pagingbuttons', function(event)
Then we any button is clicked you can get its id value like so
event.target.text
This stops any other li elements on the same page to fire the ajax call unintentionally.
You can use this javascript library (which I wrote): https://github.com/pjbonestroo/PagedList
It solves the problem of reloading, pagination, etc, and is fully customizable. It includes documentation.
It will automatically call your controller function with an ajax call, or you can add data on client-side, if you prefer.
It also has some nice features like
filtering and sorting (client- or server-side, as preferred)
debouncing to prevent too many refreshes
customizable buttons and styling, dependent on row-data
easily add/remove event-listeners to rows (and get the row-data on triggering)
Regarding your question, have a special look to the customizable buttons, so that you handle the clicks on the buttons using Javascript.

Javascript run function in background regardless the page

i need to run a function periodically regardless the page where i am. This function will get some data periodically.
I dont think that this works:
function myFunc()
{
//your code
}
//set the interval
setInterval(myFunc,2000) //this will run the function for every 2 sec.
Because it works only for the page where I am right now, so if i go to another page, function is not executed anymore.
I would like to write a function that start running when user is at index page and then is called periodically until user close the page.
Any idea? Thanks in advance!
That's not possible with javascript in the browser. When you navigate away from the page, the script will stop. You have to include a script on every page that initializes this periodical update. Or you could rewrite your application to a "single page application", which seems to be popular nowadays.
You'll need a backend application or cron-job to do that.
Another way do that would be to make an Ajax-only single page application. I guess twitter uses that model.
Depending on what your doing in the function you may be best to use a JS Worker which will run as a new thread and allow you to continue processing as much as you want in the background without having to worry about JS timeouts.
The main point here is what your asking for is near enough impossible within JS unless you use something similar to jQUery and dynamically load your pages in to a div? This would mean you still have the effect (visually) that you changing page but the browser only loads the data in.
Its very easy to in fact to load content in to a DIV using jQuery its:
$('#elementoloadid").load("/path/to/load");
You could achieve this without using jQuery but will take you longer.

Adding DOM bloat when displaying flash message

In my Rails application, when a user saves, it uses Ajax to save the post and then execute the update.js.erb file. In that file, I have some jQuery:
$('body').append('<div class="message">Saved</div>');
Because I have it this way, every time the user saves, it adds more <div class="message">Saved</div> in the body. Is there a way I can stop that or does it not matter?
A lazy (but easy) method would be to clear the other messages before showing your new one:
$('.message').remove();
$('body').append('<div class="message">Saved</div>');
First off, unless the save is happening thousands of times, it probably doesn't matter. Remeber that images are very large so a few kb of extra text in a web page pales in comparison to a few images.
Second, you have several options to only ever have one of these in the DOM:
After showing it to the user, then remove it from the DOM (perhaps on a timer).
Have one and only one message and show/hide it when needed (this is probably simplest).
Look to see if one is already in the page and reuse it.
For example, to find a previous message object (that starts out hidden) and show it for a brief period of time, you could use this:
$(".message").html("Saved").show().delay(2000).fadeOut(1000);
If you used that, you would just put the message object in your page once to start with, either in the original page HTML or just append it once in your page startup code. Then, have CSS that defaults it to hidden so it only shows when you want it to.
Or, if you're using a CSS3 transition based on a class name, you can do just use jQuery's addClass() and removeClass().

back/next button in dynamically constructed webpage (AJAX)

My question is about using Back and Next buttons (of the browser) on an AJAX (dynamical) webpage.
The solution I self came up with:
setInterval(function(){
if (location.hash != hash)
{
hash = location.hash;
app.url = window.location.href.toString().replace('http://xxxxx.nl/xxxx/#!/','')
app.handleURL();
}
}, 500);
this function reads the url(hash) and compares it with the last stored url(hash), every 0.5 second. If url has changed (back/next is pushed) it runs handleUrl() which runs more functions to dynamically build my page.
the problem is, this sort of works BUT when I click an html [A] element or when I change the url in an other way (javascript), that content will be loaded TWICE because of the setInterval()... functionality.
How can I build my HTML/Javascript in such way that my content will always be loaded once,
once when I push back/next
once when I click on an HTML element/use Javascript functions on
runtime
I searched the sh*t out of google for a solution, plz help!
You don't need a timer to check it. Just use the onhashchange event, and fire your AJAX calls when the event is called. This event isn't supported in IE versions below 8, though, so your method seems fine if you need IE support.
Also, it doesn't make sense that they're being called twice for a elements, since there's no reason for the interval to call your AJAX loader twice just because the hash was changed using an a element. You probably have an event listener attached to the a element which causes it to load the AJAX content, which wouldn't be needed since you're detecting any change in the hash, no matter how it was changed.
I suggest using a library for that. It will be tricky to make your own solution. Take a look at these:
http://www.asual.com/jquery/address/docs/#sample-usage
http://benalman.com/projects/jquery-bbq-plugin/

Categories

Resources