jQuery: Simple menu - javascript

I'm trying to learn jQuery by implementing a simple menu. I've got <div> elements that act as buttons and have links in them. I'm trying to add onclick events to the divs that navigate the browser to the link's address in the div. This is basically my pseudo-code. What would the real code be? How can I improve this? Any feedback appreciated!
// Iterate over each menu button
$('.masterHeaderMenuButton').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var url = $('a', this).attr('href');
this.click(function () {
window.location.href = url;
});
// If the user is on the page for the current button, hilight it
if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});

Try this untested example:
$('.masterHeaderMenuButton a').each(function () {
// Get the link in each button and set the button's onclick to
// redirect to the link's address
var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});
// If the user is on the page for the current button, highlight it
if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});

I don't actually use jQuery for such a simplistic task, especially if it involves page redirection. So unless you're looking to do some AJAX-style page loading, stick with standard HTML.
For that task, I use this sweet combo:
$('#nav_links li').live('click', function() {
var ajax_link = $(this).attr('rel');
loadLink(ajax_link);
});
function loadLink(link){
$('#content_window').css('position','relative');
$('#content_window').animate({
'left': '20px',
'opacity': '0'
}, 500, "swing", function() {
$.ajax({
url: '../sections/' + link,
dataType: 'html',
success: function(html) {
$('#content_window').html(html);
}
});
});
}
Awesome, right?
Here's the HTML:
<ul id="nav_links">
<li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
<li rel="features.html"><span class="purple">|</span>features<br></li>
<li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
<li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>
Have a fun.

Related

Making a single page application with ajax and get a 404 error when the page is reloaded

Basically, I'm coding a personal website and have made a single page application with ajax so content is added to the page between the header and footer when a page in the navigation bar is clicked. I had to manually code the push state and pop state in order to get the back and forward arrows working, which they do. However, the only issue left is that when I reload the page, I get an entry not found error.
I'm very new to web dev and javascript so some of my code is a little messy. I know the reload issue has to do with the added page URL not actually existing on the server.
Here are the relevant pieces of my code:
HTML:
<nav>
<ul class='nav-bar'>
<li class='nav-item'><a id='writing'>Writing</a></li>
<li class='nav-item'><a id='editing'>Editing</a></li>
<li class='nav-item'><a id='about'>About</a></li>
<li class='nav-item'><a id='contact'>Contact</a></li>
</ul>
</nav>
Javascript
//change page on nav click
$('.nav-bar li a').on('click', function(e) {
e.preventDefault();
var page = $(this).attr('id');
var file = page + '.html';
var origin = window.location.origin;
//nav color change for current page
removeActiveLinks();
$(this).parent().addClass("active");
$.ajax({
type: 'GET',
url: origin,
dataType: 'html',
success: function(response) {
$('#content').load(file);
},
error: function(error) {
console.log('There was an error', error);
}
});
window.history.pushState(file, null, '/' + page);
});
//nav for home page
$('#home').on('click', function(e) {
e.preventDefault();
removeActiveLinks();
$('#content').load('home.html')
window.history.pushState('index.html', null, '/');
});
//ensure page back functionality
window.addEventListener('popstate', function(event) {
var prevState = event.state;
$('#content').load(prevState);
removeActiveLinks();
var page_id = '#' + prevState.split('.')[0];
$(page_id).parent().addClass('active');
});
Here's what the error looks like
I would suggest something simpler, using simple load() (shorthand for ajax) and a the state of the history directly.
Not tested, but should work fine.
// Initial page load
$(document).ready(function(){
$("#content").load("home.html");
})
// Change page on nav click
$(".nav-bar li a, #home").on("click", function (e) {
e.preventDefault();
var file = this.id + ".html";
//nav color change for current page
$(".active").removeClass("active");
if(this.id != "home"){
$("#"+this.id).parent().addClass("active");
}
$("#content").load(file);
window.history.pushState(file, null, "/");
});
// Ensure page back functionality
window.addEventListener("popstate", function (event) {
var prevState = event.state;
$("#content").load(prevState);
var page_id = "#" + prevState.split(".")[0];
$(".active").removeClass("active");
if(page_id != "#home"){
$(page_id).parent().addClass("active");
}
});
But there is no /writing in the adress bar with this solution. If you insist on it, you will have to dive in more complex route settings on the server.

Laravel Ajax Pagination links refresh on second page click

I'm using Laravel 5.8 and I'm trying to make a pagination using AJAX and it's working 50% of the time. Actually, when I click on the links page at the bottoms, it renders the data perfectly, but my problem is that, the second time I press a pagination link at the bottom, it resfreshes the page. I don't want the page to reload half the time I click on pagination pages.
Here's my code for that:
ManagerController.php
public function index()
{
$users = User::paginate(30);
if (Request::ajax()) {
return Response::json(View::make('manager.usersTable', compact('users'))->render());
}
$user = User::find(Auth::user()->id);
$leagues = League::all();
$usersCount = DB::table('users')->count();
return view('manager.index', compact('user', 'leagues', 'users', 'usersCount'));
}
index.blade.php
$(window).on('hashchange', function() {
if (window.location.hash) {
var page = window.location.hash.replace('#', '');
if (page === Number.NaN || page <= 0) {
return false;
}else{
getData(page);
}
}
});
$(document).ready(function() {
$('.leagueModal').on('shown.bs.modal', function (event) {
var href = $(this).find('#href_link').val();
$(this).find('#leagueModalBtn').click(function() {
window.location.href = href;
});
});
$('.pagination a').on('click', function (e) {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});
});
function getUsers(page) {
$.ajax({
url : '?page=' + page,
type: 'GET',
dataType: 'json',
}).done(function (data) {
$('.usersTable').empty().html(data);
location.hash = page;
}).fail(function () {
console.log('Users could not be loaded.');
});
}
......... Down below is where I put my data .........
<div class="row">
<h3>Utilisateurs ({{ $usersCount }})</h3>
</div>
<div class="row">
<div class="usersTable" style="width: 100%">
#include('manager.usersTable')
</div>
</div>
usersTable.blade.php
Whatever there is in this file is not really important but I got this at the end of it:
{!! $users->render() !!}
Current situation: Causes a page reload on the second time I click on a pagination link.
What I want: To not reload the page when I click on pagination links.
What I've tried: I actually followed this source code: https://gist.github.com/tobysteward/6163902
Thanks :)
You are attaching click method to .pagination a once document is ready, however if you create a new element with same class will not have same functionality. To achieve this you have to force script to check document dynamically. Please see below example.
$(document).on('click', ".pagination a", function() {
e.preventDefault();
$('li').removeClass('active');
$(this).parent('li').addClass('active');
var page = $(this).attr('href').split('page=')[1];
getUsers(page);
});
In laravel if you are using yajra datatable add below function
function reload_table(){
table.ajax.reload(null,false);
}
and call reload_table() instead table.draw() it will not create whole table but only reload

Load AJAX content in modal and change URL

My current setup is on click a modal popups with data from the ajax action which has been passed an id, I want the URL to change on click.
But I also want it so that if you directly accessed the URL it would load say index with the modal preloaded.
Very much like https://www.myunidays.com/perks/view/shoeaholics/online it loads the URL with the content in a model then if you click/close the modal the URL changes to the index page.
I have seen related questions about changing URL on click but couldn't find anything to do with accessing URL directly (is their a rule I can add to my .htaccess).
(Any code/direction is appreciated)
Create a partial view (so that layout isnt rendered twice) and add the action to controller
public function actionViewmodal($id)
{
return $this->renderPartial('_view', array('model' => $this->findModel($id)));
}
Then within my index I did the following
$(document).ready(function() {
$('a').click(function() {
pageurl = $(this).attr('href');
var Id = jQuery(this).attr('id');
$.ajax({
type: 'POST',
data: {
'modal_id' : Id,
},
url : 'http://localhost:8888/directory/viewmodal?id='+Id,
success: function(response) {
if(response) {
$('.modal_some_wrapper').html(response);
$('#modal_'+Id).modal('show');
$(document).on('hidden.bs.modal', modal_id, function (event) {
$(this).remove();
});
} else {
alert('Error');
}
}
});
//to change the browser URL to the given link location
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});
});
Could someone example how myunidays website works with modal and URL change?

Why browser is blocking when jquery load large amounts of data?

I noticed a problem in many places and on my site, and I'm interested about solution.
Why any browser is blocking when jquery load large amounts of data?
On one site I made statistics that check over 11,000 entries what made pagination and show lists of 400 entries from the database. When I start to load that data, any function on my browser stop to work until the load is complete. The same also happens when I'm working in phpMyAdmin.
Is there a way to improve the load, or to prevent the blocking of? Thanks!
EDIT:
This is jQuery what I use:
<script>
$(document).ready(function() {
$("#results").prepend('<div class="loading-indication"><img src="loading.gif" /> Loading...</div>').load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('#if').removeClass('active'); //remove any active class
$("#results").prepend('<div class="loading-indication"><img src="loading.gif" /> Loading...</div>').load("fetch_pages.php", {'page': (page_num-1)}, function(){});
$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
});
</script>
On fetch_pages.php is a simple PHP loop with while function.
You can use this code to solve your problem :
Send request with $.ajax along with async true
<script>
$(document).ready(function() {
function getPage(pageno)
{
$.ajax({
type: "POST",
cache: false,
url: "fetch_pages.php",
data: "page="+pageno,
async: true,
crossDomain: false,
beforeSend: function () {
$("#results").prepend('<div class="loading-indication"><img src="loading.gif" /> Loading...</div>')
},
success: function (resp){
$("#results").html(resp);
$("#"+pageno+"-page").addClass('active');
}
});
}
//initial page number to load
getPage(0);
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('#if').removeClass('active'); //remove any active class
getPage(page_num-1);
return false; //prevent going to herf link
});
});

Bind bxslider after ajax call in WP

Please help me with binding bxSlider on Ajax response, tried on. , tries function after but no help (think problem with lack of JS syntax knowledge).
Here's JS:
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
$('body .bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});
});
});
I tried this:
function startCatalogSlider() {
$('.bxslider-catalog').bxSlider({pager: true,controls: true,mode: 'fade'});}
startCatalogSlider();
$('.catalog-menu-links a').click(function(event) {
event.preventDefault();
// Set class to newly selected language button
$('.catalog-menu-links li.current-menu-item').removeClass('current-menu-item');
$(this).parent().addClass('current-menu-item');
// Get new language data URL
var href = $(this).attr("href");
$.get(href, function(data) {
var ajaxCatalogSliderContent = $(data).find('.catalog-slider').html();
$('.catalog-slider').fadeOut('slow', function(){
$('.catalog-slider').html(ajaxCatalogSliderContent);
}).fadeIn();
//alert($('.catalog-slider').html());
startCatalogSlider();
});
});
But with no successful result

Categories