Change the css of a select link with jquery - javascript

I am working on an AJAX pagination and I made it by using this code.
$(document).ready(function() {
var pagination = $("#pagination");
var url = urlProviderOffers;
updateContent(function(json) {});
pagination.on('click', "ul a", function(e) {
e.preventDefault();
var page_to_visit = $(this).text();
updateContent(function(json) {});
pagination.find('ul li').removeClass('active');
$(this).parent().addClass('active');
});
function updateContent(callback, page_to_visit) {
page_to_visit = typeof(page_to_visit) != 'undefined' ? page_to_visit : 1;
$.ajax({
url: url,
data: {
page: page_to_visit
}
}).done(function(json) {
if (json.total > 1) {
pagination.find("ul li:nth-child(1)").addClass('active');
}
callback(json);
});
}
url = template_url.replace(/provider_id_to_change/, providerID);
return url;
}
});
<div id="pagination">
<ul class="pagination">
<li class="active">1
</li>
<li>2
</li>
<li>3
</li>
</ul>
</div>
The problem I am having is that, any time I click on one of the links of the pagination, a function is called and inside this function I change the active link been visited by the user.
For instance, when my page is loading, the function updateContent sets the current page been visited to 1. And after clicking on another link of the pagination, I remove all the added class and add a new active class to the selected link.
In my case anytime, when a link is clicked, is set the class of the selected link to active and automatically remove the added class and set the active class to the first link.
kindly help me solve this problem

Related

Why Ajax is not populating DIV on 2nd click?

I am loading data from URL inside a TAB div, data loads successfully on first request/click but on 2nd request/click it goes to the target link and doesn't populate the target DIV.
Anchor:
<li><a data-toggle="tabAjax" href="http://site.cx/admin/get-coach-stylish-view?userId={{userId}}" id="ajax_tab" class="media_node active span" data-target="#coach-view-stylish-ajax" rel="tooltip">Coach View (Stylised)</a></li>
Div to populate with DATA:
<!-- Coach View Stylised -->
<div id="coach-view-stylish-ajax">
</div>
<!-- Coach View Stylised End -->
JS:
<script>
$('[data-toggle="tabAjax"]').click(function(e) {
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('href'),
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
</script>
1- try to put a debugger in your code, and check that the code is being called on 2nd click. If not, then you need to rebind the click event.
2- You can try this way
<li><a data-toggle="tabAjax" href="#" data-href="http://site.cx/admin/get-coach-stylish-view?userId={{userId}}" id="ajax_tab" class="media_node active span" data-target="#coach-view-stylish-ajax" rel="tooltip">Coach View (Stylised)</a></li>
make href="#" and store url in data-href="..."
and in your javascript
<script>
$('[data-toggle="tabAjax"]').click(function(e) {
e.preventDefault();
var $this = $(this),
loadUrl = $this.attr('data-href'), //change href to data-href
target = $this.attr('data-target');
$.get(loadUrl, function(data) {
$(target).html(data);
});
$this.tab('show');
return false;
});
</script>

Open and Close Classes with jQuery

I have a fairly simple .addClass(open) function in jQuery, but am having trouble passing the right variables.
I have these two buttons in a sidebar:
<ul>
<li class="dashButton active" id="#1"><?php the_field('sidebar_text_0'); ?></li>
<li class="dashButton" id="#2"><?php the_field('sidebar_text_1'); ?></li>
</ul>
And then two divs that should open in eachother's place when it's button is clicked. mainDashWrap relates to id=#1 and editProfile relates to id=#2.
<div class="mainDashWrap dashView open">
...... content .....
</div>
<div class="editProfile dashView">
...... content .....
</div>
And my jQuery adds and removes the open class, which has display:none if there is no open class and display:block if it does have the open class.
My problem is with the //Get the attr2 part below. I don't think it's properly setting the class so that it's formatted to go into the $(newSect).slideDown() function.
$('.dashButton').click(function() {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
//Get the attr2
if ( this.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
This will add and remove the open class and hide the dashview that doesn't have the open class, but it will not add the open class to newSect or slide down newSect. How can I get attr2/newsect to set properly?
I suppose you first removed all .open in click event
$('.dashView.open').removeClass('open');
and only after that trying to slide up this elements in switchDashViews function
$('.dashView.open').slideUp('2000'...
But .open are already deleted
Upd. try not to use var keywords in this block
if ( this.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
because attr2 can be out of scope. Just
if ( this.id == '#1') {
attr2 = '.mainDashWrap';
}
else { attr2 = '.editProfile' }
Remove # from your id in your HTML, it is not a allowed character in id, (Imagine what selector will look like $(##1), pretty bad, huh?).
Add a data-attribute so that you can get rid of if() .. else() ...
HTML
<ul>
<li class="dashButton active" data-class=".mainDashWrap" id="1"><?php the_field('sidebar_text_0'); ?></li>
<li class="dashButton" data-class=".editProfile" id="2"><?php the_field('sidebar_text_1'); ?></li>
</ul>
jQuery
$('.dashButton').click(function() {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
// Do this
var attr2 = $(this).data("class");
/* Or you can do this
if ( this.id == '1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
*/
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
Make sense?
Don't include # in the ID. While it's legal in modern browsers, it's confusing and will make it difficult to access the element using jQuery or CSS selectors. Instead use
<li class="dashButton active" id="1">
Then change the if to match this:
if (this.id = "1")
I also suggest you use more meaningful IDs than just numbers.
this can be different depending on the function scope, try to use event.target instead so this.id would be event.target.id.
See your example of your code with changes:
$('.dashButton').click(function(event) {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
//Get the attr2
if ( event.target.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
I think this.id won't work. ~~You want to convert this to a jQuery object via $(this) then use the attr() method to retrieve the 'id'. So something like...~~
EDIT
Turns out this.id does work! Didn't notice the id="#1" you had in your HTML tags. Yep, as others have pointed out, that'll be the culprit.

How to keep active class when changing pages

I am trying to add an active class to nav item, depending what page your on. I am using this script:
<script type="text/javascript">
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(id).siblings().find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$(selectedolditem).siblings().find(".active").removeClass("active");
$(selectedolditem).addClass("active");
}
});
</script>
See full jsfiddle here: https://jsfiddle.net/ebo7hLo9/
It adds the active class, but it loads a new page, it disappears. What am I doing wrong?
https://jsfiddle.net/ebo7hLo9/10/ - here's a fiddle!
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", $(id).text());
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$("a:contains('" + selectedolditem + "')").addClass("active");
}
});
Your code was having issues remembering what element to grab. I think it's due to the web storage API's unfamiliarity with objects. Instead I got the text from the element that was selected, stored it in localStorage and on page load matched it with the correct element. Also there was part of your code that was dealing with finding the class "active" within the siblings() of the selected element and removing it. That complex of code is largely unnecessary. I replaced it with the class selector $(".active")
I didn't change this in the code, but I'd advise against using localStorage in favor of sessionStorage so that the storage will clear itself on tab/browser close.
For more info take a look at this previous stackoverflow post: Storing Objects in HTML5 localStorage
Here is a possible solution: https://jsfiddle.net/6yyLpma1/
$("#side-bar a").click(function () {
var id = $(this);
$('#side-bar').find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
Instead of $(id).siblings() use $('#side-bar'). Use the same logic in other location.
Using data elements and a delegate function: https://jsfiddle.net/ebo7hLo9/12/
HTML
<span id="delegateAnchor">
<div id="side-bar">
<ul>
<li>Home</li>
<li>Who we are</li>
<li>Services</li>
<li>What to expect</li>
<li>Representative clients</li>
<li>Success stories</li>
<li>Current litigation</li>
<li>What if you could not be a doctor?</li>
</ul>
</div>
</span>
Javascript
$(document).ready(function () {
$('#delegateAnchor').on('click', '#side-bar a', function() {
var $this = $(this);
var linkId = $this.data('desc');
$this.closest('ul').find('a').removeClass("active");
$this.addClass("active");
localStorage.setItem("menuSelection", linkId);
});
var selectedLinkId = localStorage.getItem("menuSelection");
if (selectedLinkId !== null) {
$('#side-bar a[data-desc="'+ selectedLinkId +'"]').trigger("click");
}
});

How to set the id of a div as cookie?

I have got a task to highlight the selected menu while refreshing the page. For that I want to use cookie.
Html code is
<div class="menuBar">
<div class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
Javascript file is
function Home() {
window.location.href = "../../home/welcome";
}
function NewTransaction() {
window.location.href = "../../EnergyCatagory/index";
}
But I have a code to set the menu as selected.But its not a good way.How can I pass the value of the selected menu to the page while refreshing?
this is the code for highlighting the menu
$(document).ready(function () {
var currentUrl = window.location.href;
if (currentUrl.indexOf("home/welcome") !== -1) {
$("#home").parent().parent().addClass('menuHeaderActive');
}
else if (currentUrl.indexOf("EnergyCatagory/index") !== -1) {
$("#newtransaction").parent().parent().addClass('menuHeaderActive');
}
else if (currentUrl.indexOf("portfolio/Index") !== -1) {
$("#portfolio").parent().parent().addClass('menuHeaderActive');
}
});
Give id for every menu item.
Then in the onclick() function of menu item set that id as cookie.
Set cookie
$.cookie("selectedId", $(this).attr('id'));
In document.ready function add selected class to the element with id obtained from cookie
You can implement it like this:
function goToLocation(sLocation, id) {
$.cookie("activediv", id);
window.location.href = sLocation;
}
in html:
Home
in jQuery ready:
$('#' + $.cookie("activediv")).parent().parent().addClass('menuHeaderActive');
Try to set cookises using jQuery as:
$.cookie("name", "value");
More you can read here:How do I set/unset cookie with jQuery?

select current link

how can i select the current link via jquery if I have a div like this:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Note I've tried:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?
Thanks
This should work:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.
Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).
Or return false.
Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
return false;
});
});
Don't forget to return false!

Categories