On my website I have multiple href's and I need to add a delay between when they are clicked and when they load. As there are hundreds of hrefs I cant have a separate js function for each one.
The two ways I have researched were, passing the contents of the href to javascript as a variable, such as:
example1
example2
example3
<script>
var href = ### CONTENTS OF SELECTED HREF ###
$(function() {
$("a").on("click", function(event) {
event.preventDefault();
setTimeout(function(){window.location.href = href;}, 1000);
});
});
Is it possible to do so using CSS?
No, that is not doable using CSS (Cascading Style Sheets, No way). You would need to use Javascript.
But yes, you do not need to write different functions for every a, just fetch the href inside the click callback and then redirect the user accordingly.
$(function() {
$("a").on("click", function(event) {
event.preventDefault();
var href = this.href;
setTimeout(function(){
window.location = href;
}, 1000);
});
});
Related
I have a dynamicpage.js script below:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
What that code does is it makes a link turn from href="/staff" to href="/#/staff" for the dynamic loading but it only changes the link if the <a> tag is wrapped in a <nav> tag so
it only works if its <nav>staff</nav>
I tried to make it ("#dynamic") in the jquery/js and added id="dynamic" to the <a> tag but it did not work.
How would I make it so I can just add id="dynamic" to the <a> tag instead of wrapping <nav> around EACH link i want to use this.
I would use event delegation instead ..
It can be attached to the document to be triggered wherever the link is located in the DOM ( and because click event is not a flooding one like mosemove)
Then simply add the 'dynamic' class to those links concerned by this behaviour
$(document).on('click', function(e){
var $t = $(e.target),
$a = $t.closest('a.dynamic');
if( $a.length ){
window.location.hash = $a.attr('href');
return false;
}
});
If I understand you correctly, though I'm not sure I do...
Just adding in an ID to a link won't do what you want, because an ID by itself doesn't mean anything to a web browser. It's the web browser that's responsible for doing Stuff when a user follows a link, which by default would be to follow that link and load a page; you're modifying the link address so that the interesting stuff is actually held in a named anchor (hence the "#") then relying on a JavaScript event listener to catch the "click" event and do something novel.
http://www.w3.org/TR/html401/struct/links.html#h-12.2.1
There's no way around the need to attach this listener to every link that needs the special treatment.
By making sure you generate HTML such that the "interesting" links have a specific common named class though, you can at least use the jQuery equivalent of document.getElementsByClassName, which ought to be simpler and faster than using a CSS selector based approach as in your example code.
http://api.jquery.com/class-selector/
You will still have to iterate over this and add listeners. Is it really worth all this JavaScript, CPU overhead and browser incompatibility risks (especially on mobile) just to override the behaviour of a link that browsers already deal with pretty adequately? All that history patching you have to do as well (whether or not it's hidden by a framework)? Just to avoid a page refresh? Personally, I'm really not sure it is!
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.
I have a jQuery function that replaces thumbnails with the main image.
This is the code that I use for replacing the main image:
$(document).ready(function(){
$(".wheelFinishThumbs a").click(function() {
var mainImage = $(this).attr("href");
var mainTemp = mainImage.replace(/-mid/,'');
var mainTemp = mainTemp.replace(/png/,'jpg');
$("#main_view img").attr('src', mainImage );
$("#main_view a").attr('href',mainTemp);
return false;
});
I use a PHP function to download (save) images by changing their header values. This is the HTML code that I use to download images
Click to download
but since "image.jpg" has to be my dynamic variable some how I've got to call this argument in the jQuery image replacement function and replace "image.jpg" dynamically each time I change the main image. I want to replace image.jpg with var mainImage from my image swapping function.
My jQuery knowledge is really limited, so If somebody can help me to do it, would be great.
This should work, assuming you are using jQuery 1.7+
Assuming your a tag markup is like this after you dynamically set the href to new image
Download Image
JavasScript
$(function(){
$(document).on("click","#main_view",function(e){
e.preventDefault();
var self=$(this);
alert("replace this with awesome code")
window.open('download.php?file='+self.attr("href")+,'_self', 'download', 'status=0');
});
});
Note that this function will work only of a single a element because we are targeting binding the functionality to the element with id main_view. Since ID's should be unique in the DOM, If you want to have the functionality to many a tags, i would add a common class selector to the a tag like this
<a class="aDownloadble" href="urltoSomeImage2.jpg" id="main_view">Download Image2</a>
<a class="aDownloadble" href="urltoSomeImage4.jpg" id="main_view">Download Image4</a>
And Update my script like this
$(function(){
$(document).on("click",".aDownloadble",function(e){
e.preventDefault();
var self=$(this);
alert("replace this with awesome code")
window.open('download.php?file='+self.attr("href"),'_self', 'download', 'status=0');
});
});
jQuery on is nnot necessary. you can simply use the click event binding directly. But if you are loading the markup of those links via ajax / injecting to the DOM dynamically, you should use on or live.
$(document).ready(){
$("#main_view a").click(function() {
// Code to run when user clicks on link
});
});
Is there any way to stop the page from loading the next page when someone clicks on a <a>
tag instead i want it to give the href value so for example "www.google.com" and then do a jquery .load()
which is like this
$(".window").load(hrefvalue);
i know i could just change all the href values to fire up a javascript function but that takes a bit of time so im just looking for the easiest way.
so i want it to do
stop the page loading the next part on a <a href click.
get the href value e.g http://www.google.com.
and then do a jquery (.load() or $.ajax()) call for the href page.
This should get you started:
$(document).on('click', 'a', function(event) {
event.preventDefault(); // Now the link doesn't do anything
var href = this.href; // The link's URL is in this variable
});
could do something like
$(document).on('click', '*[href]', function(e) {
// Whatever you're trying to do
e.preventDefault();
return false;
});
$(document).on('click','a[href]',function(){
var href = $(this).attr('href');
$.ajax(href,function(data){
$(your_container).html(data);
//data is the HTML returned
//note that ajax is bound to the
//same origin policy
//any request outside your domain won't work
})
return false;
});
...
And after then you can write your script for this anchor.
This should do it:
$("a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href");
$.ajax({
url: href,
success: function(data) {
alert('Load was performed.');
}
});
});
Is there an easy way to have JavaScript mimic a User clicking an anchor tag on a page? That means the Referrer Url needs to be set. Just setting the document.location.href doesn't set the Referrer Url.
<script>
$(document).ready(function () {
$("a").click();
});
</script>
Go here
This doesn't work because there isn't a Click() event setup for the link.
You could do:
window.location = $("a").attr("href");
If you want to keep the referrer, you could do this:
var href = $('a').attr('href');
$('<form>').attr({action: href, method: 'GET'}).appendTo($('body')).submit();
It is hackish, but works in all browsers.
document.location.href = "#wanted_Location";
Maybe something like this is what you're looking for?
$(document).ready(function () {
$("a").each(function(){
if($(this).click()){
document.location.href = $(this).attr("href");
}
});
});
There is a simpler way to achieve it,
HTML
Bootstrap is life
JavaScript
// Simulating click after 3 seconds
setTimeout(function(){
document.getElementById('fooLinkID').click();
}, 3 * 1000);
Using plain javascript to simulate a click.
You can check working example here on jsFiddle.
Okay, referer doesn't get set using document.location (as per my other answer), might work with window.navigate(url)? If that doesn't work the following might, though it's quite - ehrm - ugly:
$(function() {
$("a").each(function(){
if($(this).click()){
$('<form method="get" action="' + $(this).attr("href") + '"></form>').appendTo("body").submit();
return false;
}
});
});