Ajax request works, but with no CSS and JavaScript - javascript

Below is a snippet of code I have for an Ajax request. The request works, but when the request is processed the page appears without any of the CSS or JS (even though I have everything in the same directory). To test this I made the request point to a page on my site that already existed. Any help? Thanks in advance.
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxtest.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
ajaxtest.html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://swip.codylindley.com/jquery.DOMWindow.js"></script>
<p>Open DOM Window</p>
<script type="text/javascript">
$('.defaultDOMWindow').openDOMWindow({
eventType:'click',
loader:1,
loaderImagePath:'animationProcessing.gif',
loaderHeight:16,
loaderWidth:17
});
</script>
<div id="inlineContent" style=" display:none;">
<p>Inline Content</p>
<p>Click overlay to close window</p>
<p>Consequat ea Investigationes in enim congue. Option velit volutpat quod blandit ex. Congue parum praesent aliquam nam clari. Qui praesent quam sollemnes id vulputate. In imperdiet diam at sequitur et. Minim delenit in dolor dolore typi. Erat delenit laoreet quinta videntur id. Ii at qui eum ut usus. Quis etiam suscipit iusto elit dolor. Dolor congue eodem adipiscing cum placerat. </p>
<p>Erat usus lorem adipiscing non in. Nobis claram iusto et dolore facilisis. Claritatem decima velit decima ipsum wisi. Quinta ullamcorper sollemnes usus aliquip in. Ut aliquip velit tempor facit putamus. Habent duis et option quod facer. Delenit facer consequat seacula molestie notare. Qui tincidunt nobis lectores eleifend eorum. Decima usus facer id parum legere. Nonummy nonummy facilisis sit qui eodem. </p>
</div>

This is how it's supposed to work.
AJAX call is not, in terms of behaviour, a browser window. It will fetch ajaxtest.html and only this file. It will not attempt to fetch any other files referenced by ajaxtest.html.
If you want to put some webpage inside your document, use iframe:
<iframe id="iframe_test" src="ajaxtest.htm"></iframe>
You can then load some document to this iframe by calling:
document.getElementById('iframe_test').src = 'ajaxtest2.html';

Correction is as below.
document.getElementById('myDiv').innerHTML=xmlhttp.responseText;
Do not use double quote for getElementById
and window is not opening because you are dynamically adding DOM so events are not binding for dynamically loaded content.

I finally found the solution.
// for firing CSS after HTML response
function csstuff()
{
$('selector').css('var', 'val');
}
// for firing JavaScript after HTML response
function domWinInit(){
//include the code from
(http://swip.codylindley.com/jquery.DOMWindow.js)
}
function domClick(){
$('.defaultDOMWindow').openDOMWindow({
eventType:'click',
loader:1,
loaderImagePath:'animationProcessing.gif',
loaderHeight:16,
loaderWidth:17
});
}
The success case is when status==200 and readyState==4, fire your js & css functions after inserted the HTML response
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('myDiv').innerHTML=xmlhttp.responseText;
// CSS & JavaScript firing goes here
csstuff();
domWinInit();
domClick();
}
}
Thanks for your replays.

Related

Keep Cookie Consent Banner hidden once Users Accepted Cookies

I've managed to get the cookie consent banner to work, where the cookies aren't set when the page loads. Only once the user clicks on the "Accept" button, the cookies will set and show up within the dev tool Application. Once the "Accept" button has been clicked, the banner is hidden, but only temporarily. Because when I refresh the page, or click on a different page, the cookie consent banner shows up again, even though User has already accepted cookies.
I've tried out a bunch of stuff, and am stuck on how I can keep the banner hidden, after user has accepted the cookies.
Note: I have a custom cookie made and use the Google Tag Manager/Google Analytics cookies.
I would appreciate any help on this! Thank you!
HEAD SCRIPTS
<head>
<!-- Cookie Consent Banner -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');
</script>
<script>
function consentGranted() {
gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' });};
</script>
<script>
function dismissCookieBanner() {
gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });};
</script>
<!-- Cookie Consent Banner -->
</head>
HTML
<div role="region" aria-label="cookie-consent-banner" id="cookie-banner">
<div class="cookie-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<div class="cookie-buttons">
<button type="button" class="accept-cookies" onclick="consentGranted()">Accept</button>
<button type="button" class="dismiss-cookies" onclick="dismissCookieBanner()">Dismiss</button>
</div>
</div>
JAVASCRIPT
function consentGranted() {
var cookieConsentBanner = $('#cookie-banner');
if ( cookieConsentBanner.length ) {
if ( Cookies.get('CUSTOM_COOKIE') != 'true' ) {
var acceptCookieButton= cookieConsentBanner.find('.cookie-buttons .accept-cookies');
acceptCookieButton.on('click', function() {
Cookies.set( 'CUSTOM_COOKIE', 'true', { expires: 365 } );
cookieConsentBanner.remove();
});
};
};
};
function dismissCookieBanner() {
var cookieConsentBanner = $('#cookie-banner');
var dismissCookieBanner= cookieConsentBanner.find('.cookie-buttons .dismiss-cookies');
dismissCookieBanner.on('click', function() {
cookieConsentBanner.remove();
});
};
I would recommend using localStorage to store the cookie consent data, and then once the page loads, put the banner onscreen if no answer was given, else, not place it. Example:
function consentGranted() {
localStorage.setItem('consent', true)
var cookieConsentBanner = $('#cookie-banner');
if ( cookieConsentBanner.length ) {
if ( Cookies.get('CUSTOM_COOKIE') != 'true' ) {
var acceptCookieButton= cookieConsentBanner.find('.cookie-buttons .accept-cookies');
acceptCookieButton.on('click', function() {
Cookies.set( 'CUSTOM_COOKIE', 'true', { expires: 365 } );
cookieConsentBanner.remove();
});
};
};
};
function dismissCookieBanner() {
localStorage.setItem('consent', false)
var cookieConsentBanner = $('#cookie-banner');
var dismissCookieBanner= cookieConsentBanner.find('.cookie-buttons .dismiss-cookies');
dismissCookieBanner.on('click', function() {
cookieConsentBanner.remove();
});
};
document.getElementById('cookie-banner').hidden = localStorage.getItem('consent') != null
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<!-- Cookie Consent Banner -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');
</script>
<script>
function consentGranted() {
gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' });};
</script>
<script>
function dismissCookieBanner() {
gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' });};
</script>
<!-- Cookie Consent Banner -->
</head>
<h1>My site</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui vivamus arcu felis bibendum ut tristique et egestas quis. Nunc consequat interdum varius sit amet. Ac odio tempor orci dapibus. Eu consequat ac felis donec et odio pellentesque diam. Faucibus nisl tincidunt eget nullam. Aenean et tortor at risus viverra adipiscing at in. Lacinia at quis risus sed vulputate odio ut enim. Sagittis eu volutpat odio facilisis mauris sit amet massa. Maecenas volutpat blandit aliquam etiam erat velit scelerisque. Vitae tempus quam pellentesque nec nam. Vitae proin sagittis nisl rhoncus mattis rhoncus urna.
</p>
<div role="region" aria-label="cookie-consent-banner" id="cookie-banner">
<div class="cookie-text">Do you accept the cookie policy?</div>
<div class="cookie-buttons">
<button type="button" class="accept-cookies" onclick="consentGranted()">Accept</button>
<button type="button" class="dismiss-cookies" onclick="dismissCookieBanner()">Dismiss</button>
</div>
</div>
JSFiddle

URL anchor hash, then open a tab using another id via URL

I need a URL parameter to select a section via the hash ID (#features) and then open tab #2 within that section (Tab 1 is open by default). I want to use index.html#features and then once it has located that section, open tab #2 (#tab2).
My js below looks for the hash in the URL, if the hash is shown, trigger a click effect for the hash. I was trying to use index.html#tab2, but it won't move down to that #features section and so I'm not sure how to solve this.
The #features section is near the bottom of the page, so I need to first locate this section and then open the 2nd tab.
JS Fiddle
<article id="features">
<div class="tab-wrapper">
<ul class="tab-wrapper__tab-list" role="tablist">
<li role="presentation">
Tab One
</li>
<li role="presentation">
Tab Two
</li>
<li role="presentation">
Tab Three
</li>
</ul>
<div id="tab1" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Lorem ipsum dolor sit amet, nam an purto autem contentiones. Cum solet verear petentium ut, an incorrupte interesset sit, eu sea dicant suscipit definiebas. Ut illum habemus sententiae sea, nec nibh accusata an. Tempor dissentias ea nam. Utinam volutpat sed at, dicta errem cu est.</p>
</div>
</div>
<div id="tab2" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Vel zril putent incorrupte ei. Cu tation veniam euripidis vel, diceret minimum deserunt an ius. Eam ex probatus laboramus, cum ad noluisse suscipit, everti accusata id eam. Ius et commune recusabo, id munere alterum mei. Rebum oratio malorum usu te, no feugait inciderint eos. Eum viderer deseruisse instructior at. Nusquam expetenda eam et.</p>
</div>
</div>
<div id="tab3" class="tab-wrapper__tab" role="tabpanel">
<div class="tab-wrapper__content-wrapper">
<p>Tacimates consetetur his eu. Amet persecuti an eum, ne facete audiam mei. Pri et alia urbanitas, dicunt tacimates eos eu. Ut sit inani urbanitas. Has in equidem atomorum accommodare. Te vim decore cetero intellegebat. Saepe timeam posidonium pro te, nulla insolens adipisci ne vis.</p>
</div>
</div>
</div>
</article>
<script>
$(function () {
var hash = $.trim(window.location.hash);
if (hash) $('.tab-wrapper__tab-list a[href$="'+ hash +'"]').trigger('click');
});
</script>
Have you tried scrolling to the tab button with #tab2 in the URL? This would solve your problem with scrolling down to the features section, as the #tab2 element is on top of the features section.
A JSFiddle runs in an iframe and you need to provide the hash inside the link of the iframe. A workaround for this is just setting the hash with JavaScript. If you set window.location.hash = "tab2"; as the first line in your script section, it scrolls down and displays the second tab.
If you insist on scrolling to the #features element, you can realize that pretty easy with JavaScript. This allows you also to create an animated scroll down to the section. See this answer for more information about that: https://stackoverflow.com/a/16475234/3233827

CasperJS click not firing click event

I am having trouble with CasperJS. I load the page for our site, then try to click on the signup button. It's supposed to open a modal, but nothing happens. It works in actual browsers, and very similar functionality works in other tests on other pages.
What could I be doing wrong? What else would help you, the wider internet, help me?
casperjs --version: 1.1.0-beta3
phantomjs --version: 1.9.7
Casper test snippet:
casper.then(function() {
casper.open(DOMAIN);
});
// wait added for debugging.
casper.then(function() {
casper.wait(2500);
});
// many different ways of trying to click and debug:
casper.then(function() {
casper.click('[data-js="company-search-view-jobs-button-reg"]');
var x = casper.evaluate(function() {
var f = $("[data-js='company-search-view-jobs-button-reg']");
f.click();
var q = document.getElementById("foo");
q.click();
$('#foo').click();
return $("[data-js='company-search-view-jobs-button-reg']")[0].innerHTML;
});
// this prints the expected text, so it is definitely on the right page.
casper.echo(x);
});
//waiting in case it was slow for some reason
casper.then(function() {
casper.wait(2500);
});
// takes a screenshot. uses casper.capture under the hood.
casper.then(function() {
util.screenshot("fff", SCREENSHOT_OPTIONS);
});
From the JS with the click handler:
var $companySearchViewJobsBtnNeedReg = $("[data-js=company-search-view-jobs-button-reg]");
[...]
$companySearchViewJobsBtnNeedReg.on("click", function(e) {
e.preventDefault();
[library code for opening the modal]
The HTML on the page:
<div class="columns xlarge-8">
<div class="company-basic-info__logo left">
<img class="company-basic-info__logo-img" src="/images/logo_placeholder.png" alt="[Standard Values] logo">
</div>
<div class="header-container">
<h1>Standard Values</h1>
<button class="company-basic-info__view-jobs-button" data-cta="viewOpenJobsForCompany" data-js="company-search-view-jobs-button-reg" href="https://[internal url not really important for the question]">Sign Up</button>
</div>
<div class="company-basic-info__description">
<div class="company-basic-info__description-text" data-attr="expandable">Lorem ipsum dolor sit amet, inani labores eligendi ex cum, labitur equidem recteque eam eu. Ignota semper mentitum ad vim, aperiam volumus iracundia ne mea, eu eros movet mel. Sed ea natum elaboraret. Mel modus aliquid reformidans ei, postea putent splendide an eum.
Sanctus indoctum mea id, feugiat placerat mei ea. An scripta epicurei theophrastus has, vis eu illud principes moderatius. Facer velit sed ei, atqui dicta ornatus ea vix, nec soluta populo ei. Quis laudem nec cu, sed viderer theophrastus id.
</div>
<div class="company-basic-info__description-expander" data-attr="expander" style="display: block;">
</div>
</div>
</div>
In my case the problem was this line
casper.options.remoteScripts.push 'http://code.jquery.com/jquery-2.1.4.min.js'
The casperjs Jquery injection overwrited the addEventListeners so they were not working. Remove that line and test if it works. Modify your code to use plain javascript instead of Jquery lib.

AngularJS: How would I go about selecting a single row from an array based on ID

THIS HAS BEEN UPDATED, AND IS FUNCTIONAL Thank you #j.wittwer
http://jsfiddle.net/wittwerj/2xjuh/
I am trying to select a row from an array of posts based on ID. The goal behind selecting a single post is to create a single view where users can comment on a specific post.
I am unsure of what the best way to go about this is. I thought about just creating a model but I unsure how to select a single row in order to make that happen. I also would need to then select it with the form controller so that I can send that in the array back to ajax so that it gets posted in the array for that post.
I apologize if the code is messy firefox doesn't seem to like the formating Stack applies.
This is my JS code:(UPDATED)
var myApp = angular.module('myApp', []);
myApp.controller('FrmController', function ($scope, $http) {
$scope.visible = {
post: 1
};
$scope.posts = [{
id: 1,
content: 'Lorem ipsum dolor sit amet, eu laboramus persecuti cum, vel prompta ornatus democritum at, te alia partiendo pri. Ei quo sumo verear. Sed ad elitr aeterno disputationi, solum philosophia ex pro. Tempor essent prodesset in his, ne diam menandri vix, feugiat menandri ad cum.',
comment: ['first!!', 'second!!']
}, {
id: 2,
content: 'Facilisi pertinacia an nec. Veniam nostro commune ei pro, in mazim labores disputationi nec, cu habeo ludus deleniti ius. Id eripuit adolescens vis, mei nemore copiosae referrentur id. Pro ut ubique delicatissimi.',
comment: ['great post!', 'tl;dr', 'interesting']
}, {
id: 3,
content: 'Sed fugit error cu. In cetero albucius insolens pri, an sea velit altera constituto. Et perpetua splendide sed, te vel solum doming contentiones. Pro no omnes ridens liberavisse, ea pri tale cetero laoreet, pro te essent civibus assueverit. Assum essent appareat mei te, duo aeque consulatu et, te mel reque facilisis.',
comment: ['first to comment!']
} ];
$scope.btn_add = function (post, comment) {
if (comment != '') {
var IS_VALID = true;
}
if (IS_VALID) {
console.log("The form was sent");
post.comment.push(comment);
}
}
$scope.remItem = function (post, $index) {
post.comment.splice($index, 1);
}
});
HTML:(UPDATED)
<div ng-controller="FrmController">choose a post ({{visible.post}} is visible)
<ul>
<li ng-repeat="post in posts" style="display: inline; list-style-type: none;">
<input type="button" ng-click="visible.post = post.id" value="{{post.id}}" />
</li>
</ul>
<div ng-repeat="post in posts" ng-if="visible.post == post.id">{{post.content}}
<form>Post your Comment (for post {{post.id}})
<textarea ng-model="txtcomment" placeholder="Your Comment" style='width:550px'></textarea>
<button ng-click='btn_add(post, txtcomment);txtcomment = "";' style='margin-top:10px;'>Post Comment</button>
<h4>Comments</h4>
<ul>
<li ng-repeat="comnt in post.comment">{{ comnt }}<a style="float: right;" href="" ng-click="remItem(post, $index)">x</a>
</li>
</ul>
</form>
</div>
</div>
The simplest way I can think of is to let ng-click set a variable indicating which post is visible/being commented on. Then use that variable in ng-if to show the correct post.
<ul>
<li ng-repeat="post in posts">
<input type="button" ng-click="visible.post = post.id" value="{{post.id}}" />
</li>
</ul>
<div ng-repeat="post in posts" ng-if="visible.post == post.id">{{post.content}}
...
Here is a working demo: http://jsfiddle.net/wittwerj/2xjuh/

jQuery bug when trying to insert partial elements before() / after()?

I'm trying to wrap a div around an element (my 'template' div) by using jQuery's before() and after(). When I try to insert a closing after the selected element, it actually gets placed before the target.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Div Wrap</title>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
$('document').ready(function() {
var beforestr = "<div id=\"wrap\"><div id=\"header\">Top</div><div id=\"page\">";
var afterstr = "</div><div id=\"footer\">Bottom</div></div>";
$('#template').before(beforestr);
$('#template').after(afterstr);
});
</script>
</head>
<body>
<div id="template">
<h1>Page Title</h1>
<p>Pellentesque habitant morbi tristique senectus
et netus et malesuada fames ac turpis egestas. Mauris
placerat eleifend leo. Quisque sit amet est et sapien
ullamcorper pharetra.
<script>document.write('This script should still work and might contain variables. Please don\'t recommend concatenation.');</script>
Donec non enim in turpis pulvinar facilisis.</p>
</div>
</body>
</html>
The result is:
<div id="wrap">
<div id="header">Top</div>
<div id="page">
</div>
</div>
<div id="template">
<h1>Page Title</h1>
<p>Pellentesque habitant morbi tristique senectus
et netus et malesuada fames ac turpis egestas. Mauris
placerat eleifend leo. Quisque sit amet est et sapien
ullamcorper pharetra.
This script should still work and might contain variables. Please don't recommend concatenation.
Donec non enim in turpis pulvinar facilisis.</p>
</div>
<div id="footer">Bottom</div>
Why are my closing wrap and page divs getting placed before the target, when I'm trying to place them after() ? Is there an alternative way to accomplish this (keeping in mind I may need to call script functions within the template div)?
As I'm sure you're aware, best practices aren't what I'm going for here.
You can't insert fragments, as they need to be complete DOM elements. Instead you should use .wrap() in some spots here; it should look like this instead:
$(document).ready(function() {
$('#template').wrap('<div id="wrap">')
.wrap('<div id="page">').parent()
.before('<div id="header">Top</div>')
.after('<div id="footer">Bottom</div>');
});
You can test it out here. What this does is the effect you were after overall:
<div id="wrap">
<div id="header">Top</div>
<div id="page">
<div id="template">
<h1>Page Title</h1>
<p id="aeaoofnhgocdbnbeljkmbjdmhbcokfdb-mousedown">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Donec non enim in turpis pulvinar facilisis.</p>
</div>
</div>
<div id="footer">Bottom</div>
</div>
Don't use partials. Add your header and footer using before() and after(), but use wrap() for your wrapper. Reference http://api.jquery.com/wrap/
You cannot insert half of an HTML tag. Your code would leave an invalid DOM between the two calls.
The browser will fix up the HTML string for each call, and generate unwanted results.
Instead, call .wrap:
$('#template')
.find('script').remove().end()
.wrap('<div id="page"><div id="wrap"></div></div>')
.parent()
.before('<div id="header">Top</div>')
.after('<div id="footer">Bottom</div>')
This will also correctly preserve <script>s in the content.
Demo

Categories

Resources