Javascript only works after first refresh - javascript

I know this is by far not the first time this question is asked but I did look through every discussion I could found and none of the approaches was helpful to me (I'll list those solution-attempts further below).
My problems is a Show More/Hide Button-Javascript that only seems to work after the first refresh of the page (interestingly, this only shows up if a non-admin user visits the site - if that makes a difference).
My Code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var SHOW_MORE = 'Show More'
var COLLAPSE = 'Show Less'
$(window).load (function(){
$('a[href^="#expand"]').each(function(){
var n = parseInt($(this).attr('href').split('-')[1]);
var next_n_divs = $(this).parents('div.sqs-block').nextAll().slice(0,n)
next_n_divs.wrapAll('<div class="extra-gallery" style="display:none;"></div>');
$(this).click(function(){
var target_gallery = $(this).parents('div.sqs-block').next('div.extra-gallery')
if (target_gallery.is(':visible')){
$(this).text(SHOW_MORE);
}
else {
$(this).text(COLLAPSE);
}
target_gallery.slideToggle();
return false;
});
});
});
</script>
I figured out it might be helpful to add a
$(window).load( function() {
// ...
});
but this only seemed to 'crash' the page (maybe I applied it wrong tho).
(Here the links I already took a look at:
Javascript only works after page refresh
Rails javascript only works after reload
Rails javascript only works after reload )
thx for any help
Titus

Related

Javascript behavior between 2 different functions that I don't understand

I'm a Java developer not well-versed in front-end technologies, so I hope this question isn't too dumb. I have 2 scripts inline on an html page.
<script type="text/javascript">
function printReceipt(orderId,email) {
var printWindowSettings;
var browserUserAgent = navigator.userAgent;
if (browserUserAgent.indexOf("Chrome") > -1) {
printWindowSettings = "status=0,toolbar=0,menubar=0,height=500,width=1000,scrollbars=1";
} else {
printWindowSettings = "status=0,toolbar=0,location=0,menubar=0,height=500,width=1000,scrollbars=1,noopener=1";
}
var path = "/shop/printReceipt?orderid="+orderId;
if (email!=null)
path+="&email=" + email;
var docPrint = window.open(path, '_blank', printWindowSettings);
if (docPrint == null) console.log("window open returned null");
}
</script>
<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
window.history.back=function(){
console.log("Back Button Pressed.")
document.location='/shop/shoppingCart.seam';
}
}
</script>
printReceipt() is invoked in the onClick() handler of an anchor tag.
<div class="pull-left" style="padding-bottom:20px;"><i class="fa fa-print" aria-hidden="true" style="padding-right:6px;"></i>Print Receipt</div>
What I'm finding is that when printReceipt() is invoked, the following script (to manage the back button) gets invoked also. So when printReceipt() is called, my browser navigates to /shop/shoppingCart.seam.
Why would this be? How do I get around this?
I made a bit of research about your issue, and since you mention that you are using a third party script (which is not always the best for a developer), I found something that may help you get rid of it.
This method will need you to delete the third party script you already have (or comment it). Since we are going to handle the back button in a different way.
In the script tag where you had the following code:
bajb_backdetect.OnBack = function() {
window.history.back = function() {
console.log("Back Button Pressed.")
document.location = '/shop/shoppingCart.seam';
}
}
Replace it with this code:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/history");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/history") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("/shop/shoppingCart.seam"); //Here goes your URL
},0);
}
}, false);
}(window, location));
And now, if you did remove the third party script (or commented it), you should be able to see the expected behavior.
If you want to see more about this, there is a question similar to this that has been already answered saying the best approach for handling the window back event is doing it by yourself.
I took this information from this answer, just complemented it with the explanation and code for your specific issue. Hope it helps.
Note: If it still not working, you will need to provide a more open context of your code, since there might be something else causing it to not work.
Probably the anchor being clicked causes the browser to follow the link.
Given this:
click me
Clicking that link will run the function and then the page will reload. Your back detection script will notice that the page is being unloaded and do stuff (apparently).
Change it to:
click me
To prevent the link from being followed.

Going to a page anchor after load adding transition

I'm quite new at using jquery but learning a bit everyday. I have solved many problems searching this web but I can't seem to find any solution for this one:
The web I'm workign at the moment use quite a lot of page anchors.
I have localscroll and scrollto as jquery libraries.
I animated the transition with this little script:
<script type="text/javascript">
$(document).ready(function () {
$('.scrolllento').localScroll({ duration: 1000 });
});
</script>
and it works fine whatever I add the class "scrolllento" to the cointainer of my links.
Now the problem I have is when a link jumps to an anchor of inside different page. my client has asked me if it's possible to load the page first then move to the anchor with same web transition.
I have been working on it with my little knowdlege and this is what I have atm:
<script type="text/javascript">
$(document).ready(function () {
var nosalto = $(location).attr('href');
if (nosalto.indexOf("HistoriaBMG") > 0) {
$.fn.gotoAnchor = function (anchor) {
location.href = this.selector;
}
$('#historia').gotoAnchor();
}
});
</script>
"HistoriaBMG" is the new page and "#historia" is the anchor I want to go inside that page.
and it seems again that it works...
the problem is I have no idea how to implement now the transition as the class "scrolllento" in the container of the link going to ../HistoriaBMG is ignored.
could anyone help me? thanks so much in advance and excuse my english, hope this question is clear enough.
According to the localScroll docs:
The plugin also adds a function, $.localScroll.hash() , that checks the URL in the address bar, and if there's a hash(#an_id), it will scroll to the element. It accepts a hash of settings, just like $.localScroll. You will likely call it on document ready. Check the regular example to see it in action.
So you simply need to call $.localScroll.hash()on $(document).ready()

Jump to a page section and execute a javascript function

I'm trying to create a FAQ page using Codeigniter + Smarty + javascript
This code:
$(document).ready(function() {
$('dd').hide();
$('dt').click(function(){
$(this).next('dd').slideToggle('slow');
});
$('a.close').click(function (){ $(this).parent('dd').slideUp('slow'); });
});
and my .tpl file is something like
<dl>
<dt>Question one</dt>
<dd>Answer to question one</dd>
</dl>
I am trying to make the page jump to some question based on the url. For example: www.example.com/faq#q11 jumps to question 11. I do this using <span id='q11'> but I now have other problem. The question opens when I enter the url, I mean if I actually go to www.example.com/faq#q11 the browser takes me to the question but I have to click it to toggle the answer.
I want that when I enter the URL to some question, it toggles that answer automatically.
put this is your ready function:
if(window.location.hash)
{
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
//something like $('#'+hash_value).toggle();
}
edit: not tested but you could probably use $(window.location.hash) because window.location.hash already contains the ID selecter.
This is usually done using route services \ modules, and a lot of MVC frameworks out there come with with route services built in.
If you opt for getting this done without a 3rd party library, you can create a simple router function to handle routes for your website on DOMReady:
function ifRoute( Hashtag, Callback ){
if (window.location.hash.indexOf( Hashtag ) != -1)
Callback();
}
Then, on DOMReady, you would use this like so:
jQuery(document).ready(function(){
ifRoute( 'q11', function(){
//show answer...
//do other cool stuff...
});
});
This is a very simplistic example, and would only help for DOMReady - but I hope it's enough to help out, and at least point you in the right direction.

jQuery load file function triggers only in one situation

My jQuery script below works perfectly on all devices and PC except Windows Phone. I think it's a pretty standard coding but it gives me a problem. The #feed with the engine.php in it, does not update when I press refresh. ( only on Windows Phone)
A workaround I found is that if I cap +=1; on the #refresh click function then it works.
I am using the latest jQuery.
How can I fix this? Is there anything special about Windows Phone to make use of it ? It seems that there is something like cache, because when I refresh the page it does not chaneg. When I close the tab and open it again it takes me to the updated page.
<script type="text/javascript">
var cap = 18;
$(function() {
function loadfeed() {
$('#feed').load('engine.php?cap=' + cap, function() {
$("#loadmore").val('Show More');
});
}
loadfeed();
$("#refresh").click(function() {
loadfeed();
});
});
</script>
<div id="nav_bar">
refresh
</div>

Fancybox - Setting the parent window's global variable from within a child fancybox

Here is the issue at hand:
The overall development is being done using Ruby on rails; however, the views consist of mostly html and jQuery. Currently, I have it set up so that when a user types into a text field, they can press a small "suggest" button beneath it which opens up a Fancybox where there is a list of useful Search terms, provided by the Google Suggest API. This is all set up and working. Now I want to take this to the next step, where, from inside of the Fancybox, the users can click on one of the suggestions and it will replace the initially typed in phrase in the parent window. Sadly I am not adept at using AJAX yet so I am trying to do this via javascript. This is what I have thus far:
In the parent window:
<script type="text/javascript">
$(document).ready(function() {
var $_returnvalue = false;
$('.suggest_link').fancybox({
onClosed: function(){
alert($_returnvalue);
if ($_returnvalue != false)
{
// I will be setting the textbox value here.
}
}
});
</script>
In the partial view rendered inside of the fancybox:
<script type="text/javascript">
$(document).ready(function() {
var $_fancyvalue = false;
$(".suggestion").click(function(){
alert(parent.$_returnvalue);
parent.$_returnvalue = $(this).text();
$.fancybox.close();
});
});
</script>
Sorry if there is anything strange with this post. This is my first time asking a question here.
Define var $_returnvalue in the global scope in the parent window. Try this it will work fine.
var $_returnvalue = false;
$(document).ready(function() {
$('.suggest_link').fancybox({
onClosed: function(){
alert($_returnvalue);
if ($_returnvalue != false)
{
// I will be setting the textbox value here.
}
}
});

Categories

Resources