Triggering a Click event in jquery upon navigating to the page - javascript

I have the following navigation:
<ul id="chooseType" class="chooseType">
<li><a id="active" href="#" title="" class="active selected">Active</a></li>
<li><a id="inactive" href="#" title="" class="inactive">Inactive</a></li>
</ul>
With this script:
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function() {
$('#active').click(function(){
$('#active').addClass('selected');
$('#inactive').removeClass('selected');
$('#activeList').show();
$('#inactiveList').hide();
});
$('#inactive').click(function(){
$('#active').removeClass('selected');
$('#inactive').addClass('selected');
$('#activeList').hide();
$('#inactiveList').removeClass('hidden');
$('#inactiveList').show();
});
});
/*]]>*/
</script>
I need to be able to navigate directly to the inactive view upon clicking a link on a separate page. How do I trigger the ('#inactive').click upon accessing the page from a link on a different page? The divs that are to be shown/hidden are not included for the sake of space and simplicity.
Edit: The missing }); unintentionally disappeared with some irrelevant code I removed for clarity's sake.

The cleanest way, IMO, is to pull the anonymous functions out of the .click() handlers, give them names, then bind the #inactive function to run on load as well as on .click(), like so:
$(document).ready(function() {
var active = function(){
$('#active').addClass('selected');
$('#inactive').removeClass('selected');
$('#activeList').show();
$('#inactiveList').hide();};
var inactive = function(){
$('#active').removeClass('selected');
$('#inactive').addClass('selected');
$('#activeList').hide();
$('#inactiveList').removeClass('hidden');
$('#inactiveList').show();};
$('#active').click(active);
$('#inactive').click(inactive);
inactive();
});

Provide a GET value to the page if you click on the link to the page from a specific location.
Let's say the following is your current anchor element from the specific location in question
Click me
Change it to
Click me
On the destination page, grab the GET value
$from_value = $_GET["from"];
Then look for the value in your JavaScript
var from_value = "<?php echo $from_value; ?>";
if(from_value != "" && from_value != null){
$('#active').removeClass('selected');
$('#inactive').addClass('selected');
$('#activeList').hide();
$('#inactiveList').removeClass('hidden');
$('#inactiveList').show();
}
If a GET value is provided, the JavaScript code in question is executed. If there is no GET value, nothing happens
I am assuming you are using PHP with this solution

Related

how to call or display a div by changing url using href?

i am trying to show a div which is currently hide and inside body tag.by changing url using anchor tag attribute href.Like below---
<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
when i click on this anchor tag my url will definitely changed.and based on url i wants to display a div.
my js code...
function openCity() {
if (window.location.hash == "managevendors") {
$("#managevendors").show();
}
}
i dont know why this is not working.but i teide with different way like below..
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>
and js code.....
function openCity()
{
if (window.location.hash == "#managevendors") {
$("#managevendors").show();
}
}
but i dont want the # sing,how can i solve it.help me experience brothers.thanks in advance.
You must use the hash if you expect the navigation to work. Once you do that, you don't need to check for it, you can just show the section:
$("#ai").on("click", openCity);
function openCity() {
// The only reason this code is running is because the link was clicked.
// No need to test for it.
$("#managevendors").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You have to include the hash in the href for navigation to work -->
<a id="ai" href="#managevendors" class="tablink">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
I think the problem here is that you are using an anchor tag when you should be using a button. The reason the first way is not working is due to the page refreshing when you click the link.
Try changing your <a> to a <button>
From what I understand, you most likely need the href="#xyz" with a hash. This will keep clientside logic active without trying to solve the url and take a detour to the server for nothing. If you're going to capture that part, keep it local.
I suggest to remove the onclick handler from HTML. To capture the link you can use jQuery to keep your HTML "clean". If you must, for some odd reason, by all means you can reference onclick="openCity(this)", so the element you click on is passed directly to openCity.
// vanilla
function openCity(element){
var href = element.getAttribute('href'), // expecting a hash here
id = href.substr(1), // remove the hash
target = document.getElementById(id);
target.className += " active";
return false;
}
As Scott suggests with jQuery:
//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);
Then the function can be made dynamic by referencing the href from the clicked element:
function openCity(ev){
var el = $(ev.currentTarget),
id = el.prop('href'), // expecting a hash here
target = $(id);
// since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
ev.preventDefault();
target.addClass('active');
}
If the id was not found on the page, this will void silently.
Now if you want to work with the url as entry point, note that this will only happen on load event => share a link and someone clicks on it (with the #xyz attached) or type directly in the address bar.
// 1. bind the event
$(window).load(function(){
/*loadCity defined here or outside*/
loadCity();
});
// 2. define what happens
function loadCity(){
var id = window.location.hash, // expecting a hash here
target = $(id);
target.addClass('active');
}
Since this solution only solves state of an element, the actual show/hide part can be made in CSS. Very simple as you probably already did or with animations, transitions and so on.
.city { display: none; }
.city.active { display: block; }

Callback function not executing click after .load()

I've come to a road block and I'm hoping someone can explain where my error is. I'll do my best to explain my script, sorry if I overly break it down.
I have a div on page1.html that is being replaced by a div on page2.html via jquery's .load(). My script which is found in the <head> is as following:
<script>
$(document).ready(function(){
$(".info").click(function(event){
var gallery = event.target.id;
$("#replace").load( "folio/" + gallery + ".html #grab", function () {
jQuery("#gallery").unitegallery({
theme_enable_preloader: true,
tiles_col_width: 250,
tiles_space_between_cols: 10,
tiles_min_columns: 1,
tile_enable_image_effect:true,
tile_image_effect_type: "blur",
tile_image_effect_reverse: true,
lightbox_show_numbers: false,
lightbox_top_panel_opacity: true,
lightbox_overlay_opacity:1
});
$("#return").on("click", function(){
$("replace").load(" Portfolio1.html #replace1") });
});
});
});
</script>
The script executes when a <a id="folio1" class="info"> is clicked. A variable gallery will store the id value of the <a id="folio1" class="info"> that was clicked. I then select the <div id="replace"> which will have its content updated via Jquery's .load(). Variable gallery that is storing the id will be used inside the .load to determine the appropriate page url the new content will be loaded from. So far this works perfectly.
On success of .load() I create a call back function which executes .unitegallery(). Unitegallery() successfully executes and beautifully creates the image gallery. After unitegallery() I have another function which is waiting using .on("click" for a click event on <a id="return">. This function will perform another .load that will return <div id="replace"> back to its previous state. This is when things stop working.
Note:The selector used for the function <a id="return">, was inserted into the webpage via the first .load().
Issue: This .on("click" is not executing.
Ideas on why that portion of the script is not executing? Is the <a id="return"> loaded into the document by the first .load() not able to be selected?
Ask me questions for clarification! :)
please see my comment below if it works.
$("#return").on("click", function(){
$("replace").load(" Portfolio1.html #replace1") // you need the # because i think the event registration will not recognize 'replace'
//enter code here`
});
Also if this does not work, can you please paste your html so we can see the structure of your document.
I also just want to point out, there is nothing wrong when the event registration will be moved outside of the load scope.

Using jQuery, ajax and php to create dynamic content. But my nav bar doesn't work

I've created a website using PHP include to get all the pieces. Then i've created a content page, this page is the only page that is refreshed. It's also the only page where the information/text is canged. I've used jQuery, PHP and Ajax to do this.
Now, this all works fine and as it should, but it has created some new problems regarding the websites navigation.
The navigation is just a set of links in a list. But whenever one of them is clicked I've made it so that it gets a new class with a new style. So that the user can see where he/she is on the website. I've done this with javascript and jQuery using the .toggleClass method. And this works, but now I'm getting to the problem at hand.
So the this is the deal:
When ever I refresh the website through the browser the .toggleClass information is lost and the button loses it's class and style. Even though the page is not changed, just refreshed. Also, when I click on the "home" button in my banner to return to the frontpage the opposite happens. The last button that had .toggleClass activated keeps it's class and style even though I'm not on that page anymore, but returned to the initial index.
I know that my code is not that impressive and it might be lots of faults in it. I'm not really that skilled at this yet, I'm still learning. Anyway is there a way to work around this? or is it's simply something I've done wrong? Or maybe there is an easier and better way to make a website like this?
Here is my code:
Index.php
<?php
include("layout/header.php");
include("content/content.php");
include("layout/footer.php");
?>
load_page.php
<?php
if(!$_GET['page']) die("0"); {
$page = (int)$_GET['page'];
if(file_exists('pages/page_'.$page.'.html')) {
echo file_get_contents('pages/page_'.$page.'.html');
} else {
echo 'There is no such page!';
}
}
?>
ajax.js
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
setInterval("checkURL()", 200);
});
var lasturl = ""; // storage
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
loadPage(hash);
}
}
function loadPage(url) // AJAX function
{
url = url.replace('#page', '');
$.ajax({
type: "GET",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
success: function (msg) {
if (parseInt(msg) != 0) {
$('#pageContent').html(msg);
}
}
});
}
javascript.js
$(document).ready(function(){
$('.button').click(function(){
$('.buttonselected').removeClass('buttonselected');
$(this).toggleClass('buttonselected');
});
});
I'm not going to post all of my HTML and CSS code, that would be too much. I already have a ton of code posted. But here are the essentials you might need.
My navigation that has the links for the dynamic content/pages that is generated through Ajax.
<nav>
<ul id="navigation">
<li> <a class="button" href="#page1"> Frontpage </a> </li>
<li> <a class="button" href="#page2"> Archive </a> </li>
<li> <a class="button" href="#page3"> Stuff </a> </li>
<li> <a class="button" href="#page4"> Portfolio </a> </li>
</ul>
</nav>
The content page where the pages is added through ajax and php.
content.php
<div id="pageContent">
<!-- content comes here -->
</div>
Lastly just some notes:
Yes, I am linking to a jQuery document.
Everything works as it should, excep for the buttons.
Let me know if you want more information about something.
Thanks for taking the time to read all this!
Solving the "home" button problem:
$(document).ready(function(){
$('.button').click(function(){
$('.buttonselected').removeClass('buttonselected');
$(this).toggleClass('buttonselected');
});
$('.ce').click(function(){
$('.buttonselected').removeClass('buttonselected');
$('#frontpage').toggleClass('buttonselected');
});
});
Where's the '.ce' is the class of the "home" button in the banner and the '#frontpage' is the id of the button that needs to get the new class after the link is pressed and the page returns to the index.
"Solving" the refresh problem:
Added this code to the content page.
$(document).ready(function(){
location.href = "#page1"
});
Added this code to the #page1.
<script type="text/javascript">
$(document).ready(function(){
$('.buttonselected').removeClass('buttonselected');
$('#frontpage').toggleClass('buttonselected');
});
This makes it so that whenver the page is refreshed it returns to the frontpage.
It also makes it so that whenever someone first visits the website they will see
the correct frontpage and at the same time the frontpage button will have the .toggleClass style indicating where they are on the page.
This is still not a good solution though, imo. The optimal thing would of course be to make it so that whenever the browser is refreshed it's still at the same page on the website and with it's correct button "pressed". I will post my final code when I eventuall figure it out. Just thought I'd post what I've done so far if anyone else is looking at this and haveing the same issue.

How to pass `this` object to function through anchor link and convert it to jQuery object?

I'm having trouble with something that I'm trying to simplify. When a link is clicked, I want its CSS to be updated via jQuery. My main question is, how can I take Javascript's this object and convert it to a jQuery object for easier handling?
Here is what my code looks like:
<!-- HTML -->
load some page
load other page
// JS
function load(url, linkObj) {
loadPageWithURL(url);
$(linkObj).css('text-decoration', 'underline');
}
However, this does not work. Obviously I'm doing more than an underline when a link is selected, but you get the idea. Am I using this wrong or is it just a matter of converting the raw JS object to an object recognized by jQuery?
That function would work fine ($(linkObj) is correct), but you have your script in the href instead of on onclick attribute. So it won't ever execute.
Change:
load some page
load other page
To:
load some page
load other page
Don't use inline events! Use jQuery to bind them.
<a class="load" href="page.php">load some page</a>
<a class="load" href="other.php">load other page</a>
Then in JavaScript
$(function(){
$('.load').click(function(e){
e.preventDefault();
loadPageWithURL(this.href);
$(this).css('text-decoration', 'underline');
});
});
UPDATE: If new links are being added after the page is loaded, you need to use:
$(function(){
$(document).on('click', '.load', function(e){
e.preventDefault();
loadPageWithURL(this.href);
$(this).css('text-decoration', 'underline');
});
});
One of the advantages of using jQuery is that you can easily write unobtrusive JavaScript, it mean that you don't need to mix HTML with JavaScript. You can improve and achieve you requirements by refactoring your code as follows.
The HTML:
load some page
load other page
And your JavaScript code in one place:
jQuery(function($) {
$(document).on('click', 'a', function() {
var $link = $(this);
load($link.attr('href'), $link);
return false;
});
});
Note: The previous code will catch all links, if you want don't want to do this, you can add particular class name. Suppose the class name is load then the code should be rewritten as follows:
The HTML:
<a class="load" href="page.php">load some page</a>
<a class="load" href="other.php">load other page</a>
And your JavaScript:
jQuery(function($) {
$(document).on('click', '.load', function() {
var $link = $(this);
load($link.attr('href'), $link);
return false;
});
});
If you have any particular related to the code provided, put it on the comments.

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

Categories

Resources