I have a website with a link. When I click the link I want a smooth page transition to the next page using jQuery. I got the the HTML elements inside the barba DOM to fade out. But when the next page tries to load, all BUT the JavaScript loads.
This is my code:
(index.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<div class="container">
<span class="text1">Hey There!</span>
<span class="text2">This is my portfolio!</span>
<a id="homeLink" href="./home.html">Click me to continue</a>
</div>
</div>
</div>
<script>
$('document').ready(function(){
var transEffect = Barba.BaseTransition.extend({
start: function(){
this.newContainerLoading.then(val => this.fadeInNewcontent($(this.newContainer)));
},
fadeInNewcontent: function(nc) {
nc.hide();
console.log('stuff should be hidden');
var $el = $(this.newContainer);
var _this = this;
$(this.oldContainer).fadeOut(1000).promise().done(() => {
nc.css('visibility', 'visible');
nc.fadeIn(1000, function(){
console.log('new content should fade in.');
_this.done();
})
});
}
});
Barba.Pjax.getTransition = function() {
return transEffect;
}
Barba.Pjax.start();
});
</script>
I can see the the console logs in the console but JavaScript doesn't load.
This is the page I'm trying to load:
(home.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<canvas></canvas>
<script src="canvas.js"></script>
</div>
</div>
I get no errors whatsoever.
Also I have seen a question on here with the same problem as mine, but it was very unclear. (and does not have any answers so far)
Thanks!
In Barba, scripts don't evaluated when loading a new container. It can be done easily using Events.
Barba.Dispatcher.on('newPageReady', function (currentStatus, oldStatus, container) {
$(container).find('script').each(function (i, script) {
var $script = $(script);
$.ajax({
url: $script.attr('src'),
cache: true,
dataType: 'script',
success: function () {
$script.trigger('load');
}
});
});
});
Add this line:
document.getElementsByTagName("head")[0].innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">";
inside below function
fadeInNewcontent: function(nc) {
}
Related
I am trying to make a website that loads all pages using AJAX. Here's a simple piece of JS that does that:
$.ajax({
url: url,
type: 'GET',
success: function(html) {
document.open();
document.write(html);
document.close();
}
});
This obviously works and updates my current page content.
The problem is I want to keep one div unchanged (let's call it .player-wrapper). This div is actually an <audio> wrapper which I want to keep playing (and this is the reason I AJAXified the entire website). Is this possible?
Every time you render a page, you can initialize plugins/libraries like this:
const App = function() {
return {
init: function() {
// Do all your JS stuff here
console.log('App initialized.');
},
render: function(url) {
$.get(url, data => {
$('main').html(data);
}, 'html').done(() => {
this.init();
});
}
};
}();
$(function() {
App.init();
$(document).on('click', '[data-page="ajax"]', function (e) {
e.preventDefault();
const url = $(this).attr('href');
App.render(url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<audio class="player-wrapper" src="https://www.free-stock-music.com/music/alexander-nakarada-wintersong.mp3" controls autoplay></audio>
<main>
<h1>Initial page.</h1>
</main>
<nav>
Go to dummy page
</nav>
If you want to keep the audio tag with the player-wrapper class let's take this html as our base:
<body>
<audio class="player-wrapper"></audio>
<div class="page-content"></div>
</body>
Then with the following code you can place the html you received from the ajax request:
document.querySelector('.page-content').innerHTML = html;
Just don't write the html to the document, but place it in an already existing element like the div with the page-content class in this example.
And when you need to execute script tags in the html you can use jQuery's append method (since you are already using jQuery)
$('.page-content').append(html);
One thing you can do is copy the .player-wrapper before you write.
$(".overridebutton").on("click", function () {
var html = '<div class="override">Im a new div overriding everything except player-wrapper</div>';
var exception = $(".player-wrapper").html();
console.log(exception);
document.write(html + exception);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="everything">
<div class="sub-1">
Hello Im sub-1
</div>
<div class="sub-2">
Hello Im sub-2
</div>
<div class="sub-3">
Hello Im sub-3
</div>
<div class="player-wrapper">
I am player wrapper
</div>
</div>
<button class="overridebutton">Override</button>
I've just written a Javascript code to edit highlight product with another. You can see the code in a snippet.
The code works nicely on the first page. When I click on "Load more products" or "Next page" the script is not working and I can't figure out why.
Thank you :-)
<script>
var strMessage1 = document.getElementById("content") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/highlight-product col-sm-12 col-md-8/g,'col-sm-6 col-md-4 certain-product');
function paxioProduct() {
var href = $(".certain-product").find(".name").attr("href");
$(".certain-product .tools-wrap").append(' ');
$(".certain-product .tools-wrap").append('Detail');
}
$(document).ready(function() {
paxioProduct();
});
$(document).ajaxComplete(function() {
});
</script>
<script>
$(document).ready(function(){
$(".certain-product .img").insertBefore($(".certain-product .descr"));
});
</script>
<script>
$(document).ready(function(){
$(".certain-product .btn-detail").insertAfter($(".certain-product .btn.visible-lg-inline-block"));
});
</script>
In my project I have this code who takes results from mysql query and put it into comment DIV and a jquery code who takes me more results when I scroll down my page via a another page code
<body>
<div id="container">
<div class="comment">
<div id="comm">
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var offset = $('.comment:last').offset();
$(window).scroll(function(){
if((offset.top-$(window).height() <= $(window).scrollTop())
&& load==false && ($('.comment').size()>=5) &&
($('.comment').size()!=$('.nb_com').text())){
var theme = $('.comment').attr('idtheme');
$.ajax({
url: 'ajax_scroll.php',
type: 'get',
data: 'theme='+theme,
success: function(data) {
$('.comment:last').after(data);
offset = $('.comment:last').offset();
}
});
}
});
});
</script>
I would like to apply this javascript below for my comment DIV but it works only for the DIVS before I scroll down the page
$('#confirmdelete a').click(function(){
var id_comm=$(this).attr('id');
if(confirm("Delete?")) {
$.ajax({
url: 'commentsdelete.php',
type: 'post',
async: false,
data:{
'id_comm': id_comm
},
success:function(){
}
});
}
else
{
}
return false;
});
How I can apply this javascrip code for all the DIVs (before scrolling and after scrolling)
Thanks.
Solution 1:
Add your click function to the global scope, if the content is changed reassign:
var onclickfunc=function(){
alert("clicked");
}
$('#confirmdelete a').click(onclickfunc);
//later in your ajax
sucess:function(data){
//add the content
//reassign:
$('#confirmdelete a').click(onclickfunc);
}
Solution 2(even better):
Detect if a parent element was clicked, and than check if it was a confirmdelete element:
$(document).on("click","#confirmdelete a",function(){
//yourcode here
});
See: http://api.jquery.com/on/
Jquery function is executing twice(or the times if i go forward and then back). onLoad of LoginMenu.jsp ,WorkOrder.jsp is loaded in whatever id.
When WorkOrder.jsp loads it then loads the schedule.jsp in schedule tab defined in WorkOrders.jsp
When Schedule.jsp loads it fetches the records and prints in schedule page which consist of two bootstrap dropdown buttons and a link upon which it will take you to another page. onclick of a link present in schedule.jsp it empties the whatever div and load the SubcaseMain.jsp.
Subcasemain.jsp contains the back button upon clicked it empties the whatever div and loads the WorkOrder.jsp.so when i click on link present in schedule.jsp it goes to click(.delete) function present in WorkOrder.jsp twice and load the modal X number of times the function is present.I have checked the div it is emptied.So why the function is executing many times ?
tag is clear after calling empty method ,but its still in memory ,i have checked the firebug script tab in which it is making multiple sources of javascript.Why js is not cleared even after calling the empty method ??
LoginMenu.jsp
<link href="css_harish/demo.css" rel="stylesheet" />
<link href="css_harish/jquery.mmenu.all.css" rel="stylesheet" />
<link href="css_harish/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<link href="css_harish/bootstrap-paper.min.css" rel="stylesheet" />
<script src="js_harish/jquery-2.2.4.min.js"></script>
<script src="js_harish/jquery.mmenu.all.min.js"></script>
<script src="js_harish/bootstrap.min.js"></script>
<script src="js_harish/modernizr.js"></script>
<script src="js_harish/bootbox.min.js"></script>
<script src="js_harish/validator.js"></script>
<script src="js_harish/moment.min.js"></script>
<script src="js_harish/bootstrap-datetimepicker.min.js"></script>
<link href="css_harish/Loader.css" rel="stylesheet" />
<div class="content" id="whatever"></div>
$(document).ready(function () {
$(function () {
$("#whatever").empty();
$("#whatever").load("WorkOrders.jsp");
});
});
WorkOrders.jsp
$(document).ready(function() {
$("#schedule .showbox").show();
$("#schedule").load("Schedule.jsp");
});
$(document).on("click", ".delete", function(e) {
//delete the appointment
e.preventDefault();
alert("delete");
$("#edit_objid").val($(this).data('id'));
var objid = $("#edit_objid").val();
bootbox.confirm({
title: 'Delete Appointment',
message: 'Are you sure you want to delete this Appointment. ?',
buttons: {
'cancel': {
label: 'Cancel',
className: 'btn-default pull-left'
},
'confirm': {
label: 'Delete',
className: 'btn-danger pull-right'
}
},
callback: function(result) {
if (result) {
url="deleteAppointment.action?objid="+objid;
$.ajax({
type: 'POST',
cache: false,
async: true,
url: url,
dataType: 'json',
success: function(data) {
if(typeof data['EXCEPTION']!="undefined"){
bootbox.alert("Exception Occurs while deleting the appointment :"+data.EXCEPTION);
}else{
bootbox.alert("Deleted Successfully.");
$("#containerid").html('');
$("#containerid").html($(".showbox").html());
getSchedule();
}
}
});
}
}
});
});
Schedule.jsp
$(document).on("click", ".opensubcase", function() {
var id_number=$(this).text();
$("#whatever").empty();
$("#whatever").load("SubCaseMain.jsp?id_number="+id_number);
});
SubcaseMain.jsp
<span style="float:left" data-toggle="tooltip" data-placement="right" title="Go Back"><img
style="float: left" class="back" src="back.png" width="35px"
height="35px" /></span>
$(document).on("click", ".back", function() {
$("#whatever").empty();
$("#whatever").load("WorkOrders.jsp");
});
My guess is that you are binding multiple click events for the back button, try using
$(document).one("click", ".back", function() {});
instead
$(document).on("click", ".back", function() {});
example:
$(document).one('click', '#clickOnce', function(){
alert('clicked');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='clickOnce'>click me</button>
This has to do with how the script is parsed and put in the page DOM. Removing the script tag once it has parsed and executed does not remove it.
See this markup and code for example:
Markup:
<div class="wrapper">wrap it up
<button id="howdy">
howdy
</button>
<div id="whatever">
<div class='inside'>insidetop</div>
<script>
$(document).ready(function() {
$('#howdy').on('click', function() {
console.log('howdyclick from org');
})
});
</script>
<div class='inside'>inside</div>
</div>
<button id="test">
test
</button>
</div>
Code:(not in the markup)
console.clear();
var testthing = "<scr"+"ipt>$(document).ready(function(){$('#howdy').on('click', function(){console.log('howdyclick from test');});});</scr"+"ipt> <div class='inside'>inside</div>";
$(document).ready(function() {
$('#howdy').on('click', function() {
console.log('howdyclick from outside');
})
});
$('#test').on('click', function() {
$('#whatever').empty();
$('#whatever').html(testthing);
});
Now when you execute this, you can click the "howdy" button. you get the first line of this in console, note that the second line is from the outside handler.
howdyclick from org
howdyclick from outside
Now click the "test" button which puts NEW script and markup as you have done.
Now click the "howdy" button again - see you STILL get the response from the original code inside the "whatever" which now has new markup and script - which then adds the THIRD line. So you see the original still exists and executes.
howdyclick from org
howdyclick from outside
howdyclick from test
I put a fiddle together so you could see for for yourself here https://jsfiddle.net/8fwfoc5b/
im trying to load a piece of html inside a jquery dialog, this piece of code is located in a separated file, but sometimes fails to load it right. It happens like this :
This is how it should have been displayed.
But sometimes(many times actually) does this:
This is the code that calls the dialog
.click(function(){
var me = this;
$.ajax({
type:"POST",
url:"../CuentaEquipo.php",
dataType: "json",
data:"idEquipo="+$(this).attr("idEquipo")+"&idTorneo="+$(this).attr("idTorneo")+"&action=100",
success:function(data){
if(data.data == 1){
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
cuentas.dialog('open');
}
And this is the code i'm trying to load (AdministracionCuentaEquipo.html)
<script type="text/javascript">
$("#accioncuentas").tabs();
$(".test").button().click(function(){alert("ASDF")});
</script>
<div id="accioncuentas">
<ul>
<li>Abonos</li>
<li>Cargos</li>
<li>Saldos</li>
</ul>
<div id="abonos">
<button class="test">HI</button>
</div>
<div id="cargos">
<button class="test">HI</button>
</div>
<div id="saldos">
<button class="test">HI</button>
</div>
</div>
The only thing that works is closing and opening when this happens, but it's very annoying to do that. It's there any fix or i'm doing something wrong with the ajax or anything else?
Thanks .
I think the problem is that you are creating/opening the dialog before the HTML has properly been parsed.
From the jQuery documentation:
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed.
So try changing this code:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
to:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html", function(e)
{
$("#cuentas").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
EDIT: the line $("#accioncuentas").tabs(); might also fire too early, so you could change that script tag to wrap it in a function and call that function in your other code.
Example:
<script type="text/javascript">
function InitializeTabs()
{
$("#accioncuentas").tabs();
}
</script>
and then add the line InitializeTabs(); to your code, for example above the line $("#cuentas").dialog({.
SECOND EDIT: I actually think Dasarp is correct in saying that the $("#accioncuentas").tabs(); is the main problem. Either wrap it in a function as I suggested, or move the entire <script> tag down to the bottom of the file (below all your HTML).