AJAX after fetch, data loads multiply scripts - javascript

It's a basket (shop) script, im using ajax by scrolling down, 18 new article will appear, there is a button "ADD TO BASKET" to add them on personal account!
The problem is that on the index.php page is this code stored that gets the articles by scrolling, and it works perfect:
$(document).ready(function(){
var limit = 18;
var start = 0;
var action = 'inactive';
function load_country_data(limit, start) {
$.ajax({
url:"include/test_fetch.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#load_data').append(data);
if(data == '')
{
$('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
action = 'active';
}
else
{
$('#load_data_message').html("<img src='logo/loading-more.gif'>");
//$('#load_data_message').html("<div style='position: fixed; top: 0; left: 0; height: 100%; width: 100%; background-color: red;'></div>");
action = "inactive";
}
}
});
}
The articles are appearing on the website but by pressing "ADD TO BASKET" no action happens, this is fixed too, i have loaded all <scripts /> and <links />, but if i scroll down the currend appeared articles adds perfectly 1x article, but after scrolling down and go back up, add on basket a previously fetched article, it adds me 2x article!
When i go down to the page like after 4 or 5 fetches, and go back up on top to the first fetch, and press "ADD TO BASKET" it adds me 4x article (the same article 4 or 5 times).
After every fetch a script is loading custom.js to make the add to basket action possible, and obviously it calls it in one click x times it depends from the fetch time.
Here is the test_fetch.php file that will be loaded after the scrolldown:
<script src="catalog/view/javascript/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="catalog/view/javascript/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<link href="catalog/view/javascript/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="catalog/view/theme/OPC080192_1/stylesheet/stylesheet.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="catalog/view/theme/OPC080192_1/stylesheet/megnor/custom.css" />
<link rel="stylesheet" type="text/css" href="catalog/view/theme/OPC080192_1/stylesheet/megnor/bootstrap.min.css" />
<script type="text/javascript" src="catalog/view/javascript/megnor/custom.js"></script>
<script type="text/javascript" src="catalog/view/javascript/megnor/jstree.min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/megnor/jquery.custom.min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/megnor/doubletaptogo.js"></script>
<script src="catalog/view/javascript/common.js" type="text/javascript"></script><link href="http://opencart.templatemela.com/OPC08/OPC080192/OPC1/index.php?route=product/category&path=17" rel="canonical" />
<link href="http://opencart.templatemela.com/OPC08/OPC080192/OPC1/index.php?route=product/category&path=17&page=2" rel="next" />
<link href="http://opencart.templatemela.com/OPC08/OPC080192/OPC1/image/catalog/cart.png" rel="icon" />
//php add basket functions
<script src='assets/js/custom.js'></script>
<?php
// The articles and query
// ...
?>
So the fetched data doesent work without all the scripts, but the previous articles are calling same function by adding x times...
My question is how to fetch data without the scripts, i want test_fetch.php to use the script from index.php from where they are called to not repeat the scripts!
Hope i made it clear enough!

Related

Saving a cookie for darkmode/lightmode JS - Issues

I am trying to make the cookie load when the body does, and then check what value it is. If darkmode = true, then it should display css/cssmain.css. If it is false, it should display css/csslight.css. The cookie works: If I use the button to switch from dark to light, it changes darkmode from true (dark) to light (false) and vice-versa. It even stays when I refresh the page, but the css switches to its default file.
Basically, I can not figure out how to make darkMode go into the if statement in my javascript. I tried it with onload="getCookie(darkMode)" to try and put the cookie darkMode's value (true or false) into the script. It seems to just not run the script, because even if I add an alert, the alert does not pop up when I use the button.
HTML:
<head>
<title>Freshwater Fish</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/cssmain.css">
<link rel="stylesheet" type="text/css" href="css/desktopview.css">
<link rel="stylesheet" type="text/css" href="css/mobile.css">
<link rel="stylesheet" type="text/css" href="css/slides.css">
<link id='css_theme' rel='stylesheet' type='text/css' href='css/csslight.css'>
<script src="js/fullstackfrog.js"></script>
</head>
<body onload="getCookie(darkMode)">
<button class="lightmodeButton" onclick="document.getElementById('css_theme').setAttribute('href', document.getElementById('theme').value, document.cookie = 'darkMode=true'); if (document.getElementById('theme').value == 'css/cssmain.css'){ document.getElementById('theme').value = 'css/csslight.css'; document.cookie = 'darkMode=true';} else{ document.getElementById('theme').value = 'css/cssmain.css'; document.cookie = 'darkMode=false';}">Light/Dark</button>
<input type="hidden" id="theme" value="css/cssmain.css">
</body>
</html>
JS (fullstackfrog.js):
function getCookie(name) {
if (name) {
document.getElementById('theme').value = 'css/cssmain.css';
}
else {
document.getElementById('theme').value = 'css/csslight.css';
}
}
Do you know how cookies work? document.cookie will just stay the same. You need to write something to get the cookie and parse the value from document.cookie. Try reading https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie and use the examples.

Getting a loading scren to work with Polymer

I'm trying to get a loading screen to work in Polymer, as seen in this Gist: https://gist.github.com/SlicedSilver/f2e93a5995f84d9cd512
The idea's pretty simple: the entrypoint is a lightweight HTML file that renders the loading screen, whose body contains an onload callback that loads up the Polymer app via the DOM once that lightweight page is rendered.
It works beautifully on desktop browsers. On mobile browsers the filestoload.html is never getting loaded (but also isn't throwing any errors), so the loading screen just stays there and the app never loads. The full code is below, but particular attention goes to this line:
tag.setAttribute('onload', 'polymerLoader.insertPolymerApplication()');
That onload event never fires and never throws an error. I've tried catching it both through the DOM and with a proper event hander to no avail. I've even tried taking it out of the hands of the JS altogether as a sanity check, adding the link to the HTML file like so:
<link rel="import" href="/filestoload.html" onload="polymerLoader.insertPolymerApplication()" >
Same result - displays the app on desktop, but just shows the loading screen on mobile. I'm fresh out of ideas. Any help?
....
Here's the lightweight entry point (index.html)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<link rel="shortcut icon" type="image/png" href="/assets/images/favicon.ico"/>
<title>GreenMaven</title>
<meta name="description" content="greenmaven description">
<script src="assets/js/polymerAppLoader.js"></script>
<style type="text/css">
.loading {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
z-index: -500;
display: block;
}
</style>
</head>
<body onload="polymerLoader.loadPolymerApplication()">
<div id="loader" class="loading">
<img src="assets/images/gears.svg" />
</div>
</body>
</html>
And here's the JS that loads the rest of the Polymer app:
'use strict';
/* global polymerLoader */
/*jshint unused:false*/
/*jshint -W079*/
// This is the normal conditional loader for the Web components Polyfill
if ('registerElement' in document && 'createShadowRoot' in HTMLElement.prototype && 'import' in document.createElement('link') && 'content' in document.createElement('template')) {
// We're using a browser with native WC support!
} else {
// Add web components polyfill...
document.write('<script src="bower_components/webcomponentsjs/webcomponents.lite.js"><\/script>');
}
var polymerLoader = (function() {
// Function for creating a link element and inserting it into the <head> of the html document
function addLinkTag(elementType, address, shim, loadTrigger) {
var tag = document.createElement('link');
tag.rel = elementType;
tag.href = address;
if (shim) {
// add the shim-shadowdom attribute
tag.setAttribute('shim-shadowdom', '');
}
if (loadTrigger) {
// This file needs to be loaded before inserting the Polymer Application
// when finished loading it will call the polymerLoader.insertPolymerApplication() function
tag.setAttribute('onload', 'polymerLoader.insertPolymerApplication()');
expectedCalls++;
}
document.getElementsByTagName('head')[0].appendChild(tag);
}
var pgApploaded = false;
function loadPolymerApplication() {
// Only insert once.
if (!pgApploaded) {
addLinkTag('import', 'filestoload.html', false, true);
pgApploaded = true;
}
}
// Counter variable for insertPolymerApplication() calls
var callCount = 0;
var expectedCalls = 0;
function insertPolymerApplication() {
callCount++;
// Only when callCount >= expectedCalls
// The application is only inserted after all required files have loaded
// for the application to work.
if (callCount >= expectedCalls) {
// here is the html that is inserted when everything is loaded.
document.querySelector('body').innerHTML += '<template is="auto-binding" id="app"><polymer-app id="main-app"></polymer-app></template>';
document.getElementById('loader').style.display = 'none';
}
}
return {
insertPolymerApplication: function() {
insertPolymerApplication();
},
loadPolymerApplication: function() {
loadPolymerApplication();
}
};
})(document);
And finally, here's the filestoload.html file that has the links and scripts that would usually be found in the Polymer index.html:
<!doctype html>
<!-- Here is where you put the scripts required by the page, that would normally be -->
<!-- included in the index.html page, you can still use grunt/gulp build functions on these -->
<!-- will be replaced with elements/elements.vulcanized.html -->
<link rel="manifest" href="/manifest.json">
<link rel="import" href="/src/greenmaven-app/greenmaven-app.html">
<link rel="stylesheet" href="assets/css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<!-- endreplace-->
<!-- build:js scripts/app.js -->
<script src="properties_base/farmhacker-properties.js"></script>
<!-- endbuild-->
<!-- build:js scripts/thirdparty.js -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script>
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - $('#navbar').height()
}, 1000);
return false;
}
}
});
});
</script>
<!-- endbuild-->
Turns out to be some kind of bug in the Polymer build, probably related to another error where running polymer build was resulting in the app throwing a bunch of 404 errors from bower components.
When I did a raw deployment (without building/vulcanizing) to the server, everything worked fine on both desktop and mobile, and without the errors.

How do you window.onload Javascript classes?

I'm trying to dynamically change my html by calling my Javascript class in jQuery. I keep getting an Uncaught Reference error. I know I have to window.onload my class somewhere. I've tried to load it before and after the class, before and after my jquery, right before the end of my HTML body, but I keep getting Uncaught Reference errors for the class I'm calling and the prototype (randomCard()) that I use in my jQuery.
I've also tried switching the order of script files at the end of my HTML body. I'm new to Javascript.
game.js
function CardsAgainstHumanity () {
this.blackCards = [
"How did I lose my virginity?",
"Why can't I sleep at night?",
"What's that smell?",
"I got 99 problems but ______________ ain't one.",
"Maybe she's born with it. Maybe it's ______________.",
"What's the next Happy Meal toy?",
"Here is the church. </br> Here is the steeple. </br> Open the doors </br> And there is ________________.",
"It's a pity that kids these days are all getting involved with _______________."
];
this.whiteCards = [];
this.score = 0;
randomCard();
}
CardsAgainstHumanity.prototype.randomCard = function () {
var random = this.blackCards[Math.floor(Math.random() * this.blackCards.length)];
return random;
};
index.js
$(document).ready (function() {
$(".black-cards").on("click", function () {
$(this).text(randomCard());
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Cards Against Humanity</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link type="text/css" rel="stylesheet" href="css/style.css" media="screen">
</head>
<body>
<div class="container">
<div class="black-cards"> </div> <!-- Black Cards -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="js/game.js"></script>
<script src="js/index.js"></script>
</body>
</html>

Rotating Banner / Carousel With Other Web Parts

On my website's homepage, I'm looking to incorporate a rotating banner.
I have a selection of images (4), which currently change every 5 seconds.
However, what I would really like is to develop something similar to what Oracle has done - http://www.oracle.com/index.html
You can see their banner is made up of 3 parts:
1) The main image in the middle.
2) A header - that displays an icon for each image.
3) A footer which is by default hidden, but slides up upon a selection.
Any ideas of how I could even get started? I am using HTML and jQuery.
Thanks
Update 29-05-13
Apologies forgot to upload my current code:
HTML:
function rotateBanners(elem) {
var active = $(elem+" img.active");
var next = active.next();
if (next.length == 0)
next = $(elem+" img:first");
active.removeClass("active").fadeOut(200);
next.addClass("active").fadeIn(200);
}
function prepareRotator(elem) {
$(elem+" img").fadeOut(0);
$(elem+" img:first").fadeIn(0).addClass("active");
}
function startRotator(elem) {
prepareRotator(elem);
setInterval("rotateBanners('"+elem+"')", 2500);
}
#rotator img { position: absolute; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<link href="rotate.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript">
$(window).load(function() {
startRotator("#rotator");
})
</script>
</head>
<div id="rotator">
<img src="https://dummyimage.com/600x400/000000/fff&text=1" />
<img src="https://dummyimage.com/600x400/000000/fff&text=2" />
<img src="https://dummyimage.com/600x400/000000/fff&text=3" />
<img src="https://dummyimage.com/600x400/000000/fff&text=4" />
</div>

Multiple script tags not working in my page

Ok, I'm building a website for a friend, I'm currently using jquery-1.4.3.min.js, corners.js, equalcols.js, and a pre-load image script in the head. Everything works great.
Problem is, I now need FancyBox (LightBox alternative) for a page and it won't seem to work! I know it's because something is conflicting with another but I have no idea what. Is it the order in the head? Or something else? Have tried LightBox and that doesn't work either.
It either doesn't work and stops the EqualCols.js from working, or everything else works EXCEPT the FancyBox for the mini-image gallery that is needed.
The head code is as below: (without FancyBox in there)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
<!-- PRELOAD MENU IMAGES BEGINNING -->
<script>
var myimages=new Array()
function preloadimages(){
for (i=0;i<preloadimages.arguments.length ;
i + myimages [ i ] =new Image ( myimages [ i ]
src=preloadimages.arguments[i] } Enter path of images to be preloaded
inside parenthesis. Extend list as desired. preloadimages ( images /
home-h.png " images / about-h.png " images / services-rates-h.png "
images / past-work-h.png " images / contact-h.png " images /
shop-specials-h.png " images / free-quote-h.png " images /
book-now-h.png ")
</script>
<!-- PRELOAD MENU IMAGES END -->
<!-- stop curvery corners error in IE -->
<script type="text/javascript" src="js/corners.js"></script>
<script type="text/javascript">
var curvyCornersVerbose = false;
</script>
<!-- stop curvery corners error in IE -->
<!-- EQUAL COLS START -->
<script src="js/equalcols.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#left-col,#right-col').equalCols();
});
</script>
<!-- EQUAL COLS END -->
</head>
Is anyone able to tell me where I'd need to put the FancyBox coding for everything to work? Or what else I can do to get it to work? What are the rules? I've researched on Google and can't seem to find the answer I'm after.
The FancyBox code I need to implement is:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
Do I need the top line there if I'm using this already?:
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
Any help much appreciated.
replace:
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
with:
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
Fancybox code:
$(document).ready(function() {
$('#single_image').fancybox();
});
below code is working sample - the fancybox iframe version.
make sure that you add anchor tag in your html/jsp
<!-- The popup iframe . The href value will be updated dynamically -->
<a class="iframe" id="iframe" href="/YourApp/imagePopup.do"></a>
the include block is as follows
<script type="text/javascript" src="/js/jquery/fancybox/jquery.easing-1.4.pack.js"></script>
<script type="text/javascript" src="/js/jquery/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
/**
jquery ready function
*/
$(document).ready(function(){
// popup for showing
$("a.iframe").fancybox({
'autoDimensions':false,
'width' : 770,
'height' : 'auto', // height is controlled using jquery.fancybox-1.3.4.css line 79
'centerOnScroll' : true,
'scrolling':'auto',
// 'autoScale': true,
'hideOnOverlayClick' : false,
'enableEscapeButton' :true,
'hideOnContentClick': false,
'type':'iframe'
,'onStart' :function(){$.fancybox.showActivity();}
,'onClosed' :function(){ }
});
}); // end ready

Categories