Jquery HTML() working on all pages except for one? - javascript

This scripts pulls the content from an FAQ page and injects it into a modal.
The script works fine on everything, but the cart page, all of the console logs fire, my response returns successfully, but .html() doesn't add the response to the DOM.
<div id="SafetyPolicyModal" class="safety-policy-modal">
<div class="modal-content">
<div class="close-btn" safety-modal-close-btn>×</div>
<div class="content-render-section"></div>
</div>
</div>
<script>
$(document).ready(function(){
$('.container').on('click','[safety-policy-link]',function(e){
e.preventDefault();
console.log('1')
$("#SafetyPolicyModal").css("display", "block");
console.log('2')
});
$(document).on('click','[safety-modal-close-btn]',function(e){
e.preventDefault();
$("#SafetyPolicyModal").css("display", "none");
});
$.ajax("/pages/safety-liability?view=no-index").then(response => {
console.log("!!!!!!")
$(".content-render-section").html(response);
console.log(response)
console.log('done')
})
});
</script>

My guess is that this particular page has multiple elements with class content-render-section and the one you want to target is not the first.
Be specific with your selector to target the right one. FYI, you can use jQuery's .load() method to make the code simpler
// Target the content-render-section within your modal
$("#SafetyPolicyModal .content-render-section")
.load("/pages/safety-liability?view=no-index");

Related

How can I use Ajax reload without breaking all jquery events?

I'm trying to reproduce the loading effect we can see on the google material.io website : when selecting a menu item, the content and url change, but the sidebar doesn"t move, as if only the content was changing..
can someone can explain me how to do this ? is it like the tehcnique described on css ticks tutorial "dynamic page replacing content" or something more like ajax ?
I have this code in html :
<div id="containerWrapper">
<div class="flex-row">
<div id="menu" class="flex-col-xs-12 flex-col-md-2 generator_menu">
<nav role="navigation" id="navigation" aria-label="Menu principal">
MY MENU HERE
</nav>
</div>
<div id="contentWrapper" class="flex-col-md-10">
<div id="guts">
<div class="flex-col-xs-12 generator_main">
MY CONTENT HERE
</div>
<div class="flex-col-xs-2">A sidebar dynamic TOC</div>
</div>
</div>
</div>
</div>
<footer></footer>
And the Ajax Code:
$("#menuList a").on('click',function(e){
e.preventDefault();
pageurl = $(this).prop('href');
$.ajax({url:pageurl,success: function(data){
$('#contentWrapper').html($(data).find('#guts'));
// Rerun Prism syntax highlighting on the current page
Prism.highlightAll();
return false;
}});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
$(window).bind('popstate', function() {
$.ajax({url:location.pathname,success: function(data){
$('#guts').html(data);
}});
});
My problem:
-All my jquery events are in a dedicated file, wrapped in a jQuery(document).ready(function($) {}.
-If I put my ajax code like this, everything works except the ajax call..If I wrap my ajax code in a jQuery(document).ready(function($) {}., ajax works but all my other jquery events are broken when I click on any menu item and reload the page.
So is there a simple trick to make ajax works together with others jquery functions ?
Ok, finally I followed an answer given here..
In a js file, I wrapped my ajax call in a jQuery(document).ready(function(){}/
In a separate file, I wrapped all my jquery code in a function (scroll functions, clicks on menu function, filters, show/hide functions etc.):
function initialise(){}
Then in this same second file, at the end, I throw initialize function when document is ready, and when Ajax is complete :
$(document).ready(function(){
initialise();
});
$(document).ajaxComplete(function () {
initialise();
});
Now everything looks fine..
If there is a better way, I'll be glad to learn more on this..

Jquery Animate overlapping on Loading Image

I am working on a project in which the navigation does not really changes pages but gets data using services based on which navigation link I click and update data using jquery .html() method, I want to use a loader that shows up on clicking any link and hides the content, when ajax services is successfull i want to remove the loader and show back the content, but somehow the animations are overlapping causing animations to fail,
in example code here i am not using ajax to update my page but a simple button
and jquery to update the data
<body>
<div id="loader">
<img src="loader.gif" alt="">
</div>
<br>
<div id="content">
This is the content
</div>
<input type="button" id="update" value="Update Data">
</body>
<script>
function showContent(){
$('#loader').fadeOut(200).promise().done(function(){
$('#content').fadeIn(200).promise().done(function(){
});
});
}
function hideContent(){
$('#content').fadeOut(200).promise().done(function(){
$('#loader').fadeIn(200).promise().done(function(){
});
});
}
$("#update").click(function(){
hideContent();
$("#content").html("New Data");
setTimeout(showContent(), 10000);
});
</script>
on clicking update, this should happen
content should disappear,
loader should appear,
update content,
loader disappear,
content appear,
but i get both loader and content appeared in the end
I used setTimeout to give some delay but it doesnt works , i also used some flags earlier but that didnt work too .
JsFiddle : JsFiddleLink
Why use setTimeout()? You can return, chain the promise
function showContent(){
return $('#loader').fadeOut(200).promise().done(function(){
return $('#content').html(data).fadeIn(200).promise()
});
}
function hideContent(){
return $('#content').fadeOut(200)
.done(function() {
this.empty();
return $('#loader').fadeIn(200).promise()
});
}
$("#update").click(function() {
hideContent().then(showContent)
})

.click doesn't work properly on jquery

PHPstorm spoiled my files just now, so I have to rework everything. And for some reason I can't get this working - click event just don't happen at all, neither with $("body"). It does work with $(document).on(...) though.
(script is inside head and script tags)
$("#cover").on('click',function(e) {
$(e.target).removeClass("no");
$(e.target).addClass("yes");
});
<body>
<div id="button"></div>
<div id="cover">
<div class="rows" id="row1"></div>
<div class="rows" id="row2"></div>
<div class="rows" id="row3"></div>
<div class="rows" id="row4"></div>
<div class="rows" id="row5"></div>
<div class="rows" id="row6"></div>
</div>
</body>
Code is executed in the order in which it's found on the page. So this:
$("#cover")
Needs to be executed after this is added to the page:
<div id="cover">
Otherwise that element won't be found by that selector, because it doesn't exist yet.
One approach is to move the JavaScript code to the bottom of the page. (Or at least to after the target element exists.) Another is to wrap it in the jQuery function which will attach it to the document's ready event:
$(function () {
// add your code here
// this will execute after the DOM is completely loaded
});
Try doing this. It will execute once your DOM is ready.
$(function(){
$("#cover").on('click',function(e) {
$(e.target).removeClass("no");
$(e.target).addClass("yes");
});
});
You could try reverting your changes in PHPStorm by right-clicking the folder, navigating to Local History -> Show History -> right click file(s)/folder(s) and select Revert Changes.
If that doesn't work do the following:
Move your javascript to the bottom of the page
Wrap the click with $(document).ready(...)
For debugging purposes do console.log($("#cover")); as your first line before binding a click event to see if jQuery object length is 1 or 0. If 1 the element is matched and found, if 0 then element doesn't exist or no match found.

How to make both href and jquery click event work

I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>
I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.
You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();
Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle

Load a page fragment into a Twitter bootstrap Modal

Is it possible to load a page fragment using Twitter bootstrap's modal components? I want to load a page into the modal, but I only want a section of it. For example, I want the form on the page without the wrapping navigation. I've done this type of thing before using jquery tools overlays and jquery's .load function. But the modal stuff doesn't allow for this type of information to be passed in.
Here is some example text I'm working with:
<a tabindex="-1"
href="metadata.html"
id="metadata-link"
data-target="#modal"
data-toggle="modal">Metadata</a>
<div id="modal" class="modal hide fade in" style="display:none;">
<div class="modal-header">header<a class="close" data-dismiss="modal">x</a></div>
<div class="modal-body"></div>
<div class="model-footer">footer</div>
</div>
<script>
$(document).ready(function() {
$('#metadata-link').modal({show:false});
});
</script>
The 'metadata.html' page is a full html document. The contents of this page get loaded into the '.modal-body' element as expected. But the nothing displays...
If I switch the 'metadata.html' page for a page that contains only a 'div' contents, the modal displays.
Does anyone have any idea why this would happen?
You can do it manually:
<script>
$(document).ready(function() {
$('#metadata-link').click(function(){
$.ajax(
{
url:'url-to-load-page',
success: function(response){
//do what ever you want here to extract the part you want
$('#modal-div-content').html(adapted-response);
$('#modal').modal('show');
}
});
});
});
</script>
bootstrap uses the jquery load method which allows a URL and a fragment selector to be specified:
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
So in my case (adding a musician) i could use a normal link tag like this:
</i> Add
Which extracts the form element from the container div and shows it in the newItemModal modal. This approach allows me to re-use the modal for other items
Declaring the fragment id using data-remote worked for me:
<a href="remote.html" data-remote="remote.html #fragment" data-toggle="modal" data-target="#modal">

Categories

Resources