Catching in page links with jQuery - javascript

Hi i want to trig a function when user click in page links for example abc.com/hello.html#variable1 i want to catch #varible1 and execute a function.

If you want to grab the string after the hash:
$("a[href*='#']").click(function() {
var hash = this.href.replace(/.*#(.*)$/, '$1');
// do something
return false
});

Capture the hash and substring it out:
$("a[href*='#']").click(function(e){
var hash = $(this).attr('href').substring($(this).attr('href').indexOf("#"));
//hash = #var
function(hash);
});

To attach logic to all hash-links, you can do the following:
$("a[href^='#']").click(function(e){
// user clicked an inpage link
});

If you want to trigger a function for links with hashes that are dynamically inserted, use this:
$(document).click(function (event) {
var target = $(event.target);
if (target.filter("a[href*='#']").size() > 0) {
var hash = target.attr("hash");
// Do something with hash.
event.preventDefault();
}
});

Related

How to prevent Wordpress built-in “browse link” entering the data in wp-editor

Working with Wordpress Meta Box and I used the code of Dale Sattler from this How can I use the built in Wordpress “browse link” functionality? to create a custom field with wp browse link it works fine, but it inserted the data in wp-editor too.
I try to prevent the default event using code here Use WordPress link insert dialog in metabox? but doesn't work, I try that code too but it have a bug too.
here is my code
var _link_sideload = false; //used to track whether or not the link dialogue actually existed on this page, ie was wp_editor invoked.
var link_btn = (function($){
'use strict';
var _link_sideload = false; //used to track whether or not the link dialogue actually existed on this page, ie was wp_editor invoked.
var input_field = '';
/* PRIVATE METHODS
-------------------------------------------------------------- */
//add event listeners
function _init() {
$('body').on('click', '.link-btn', function(event) {
_addLinkListeners();
_link_sideload = false;
input_field = $(this).attr('href');
var link_val_container = $(input_field);
if ( typeof wpActiveEditor != 'undefined') {
wpLink.open();
wpLink.textarea = $(link_val_container);
} else {
window.wpActiveEditor = true;
_link_sideload = true;
wpLink.open();
wpLink.textarea = $(link_val_container);
}
return false;
});
}
/* LINK EDITOR EVENT HACKS
-------------------------------------------------------------- */
function _addLinkListeners() {
$('body').on('click', '#wp-link-submit', function(event) {
var linkAtts = wpLink.getAttrs();
console.log(linkAtts);
var link_val_container = $(input_field);
link_val_container.val(linkAtts.href);
_removeLinkListeners();
return false;
});
$('body').on('click', '#wp-link-cancel', function(event) {
_removeLinkListeners();
return false;
});
}
function _removeLinkListeners() {
if(_link_sideload){
if ( typeof wpActiveEditor != 'undefined') {
wpActiveEditor = undefined;
}
}
wpLink.close();
wpLink.textarea = $('html');//focus on document
$('body').off('click', '#wp-link-submit');
$('body').off('click', '#wp-link-cancel');
}
/* PUBLIC ACCESSOR METHODS
-------------------------------------------------------------- */
return {
init: _init,
};
})(jQuery);
please help, please ....
Ok I think I found a way to remove the link from the content. In your submit event you need to add:
$('body').on('click', '#wp-link-submit', function(event) {
var linkAtts = wpLink.getAttrs();
var link_val_container = $(input_field);
link_val_container.val(linkAtts.href);
var $frame = $('#content_ifr'),
$added_links = $frame.contents().find("a[data-mce-href]");
$added_links.each(function(){
if ($(this).attr('href') === linkAtts.href) {
$(this).remove();
}
});
_removeLinkListeners();
return false;
});
$('#content_ifr') is the iframe that loads tinymce editor with content inside. Since the iframe is loaded from the same domain you can mess around it (luckily). So you just go through its contents and you're looking for anchors that have data attribute called mce-href, and if the link that you've just added has the href value as the one you've added it removes them.
I re did this part of the code because I've noticed that all the links in my content had this attribute so you cannot just remove all anchors that have
data-mce-href attribute because that would remove all of them. And you only want to remove those you've added in your metabox.
This did the trick for me :)

Can I add onmouseover attribute to run only once?

Say I have a link like the following:
<a class="link" href="www.rich.com" onmouseover="go(this)">Link</a>
Is there a way to configure the onmouseover event, calling go(this) to run only a single time while still using the inline onmouseover=<some code> notation? I want it defined inline, not with a JavaScript call.
Currently, I have this, but it is not what I want:
$(".link").one('mouseover', function(e) {
// do something
});
You can nullify the onmouseover binding afterwards:
<a class="link" href="www.rich.com" onmouseover="go(this); this.onmouseover = null;">Link</a>
Using Vanilla JS:
const link = document.querySelector('.link');
link.addEventListener('mouseover',
() = window.open('your url'),
{ once : true }
);
ref: How can I add an event for a one time click to a function?
You could set a var that indicates whether it has been triggered or not...
var triggered = false;
$(".link").one('mouseover', function(e) {
// do something
if(!triggered)
{
triggered = true;
// and whatever else you want to do
}
});
Alternatively you can do something like this :
var check = 0;
$(".link").on('mouseover', function(e) {
if(check == 0 ){
// do something
check = 1;
}else {
return false;
}
});

Changing href value from JavaScript

I have this example in JsFiddle.
http://jsfiddle.net/PtNfD/114/
Yahoo
Not working
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
The href change works in the first link, but not in the second. How can I make it work for both links??
The number of links in my page is dynamic, because I create the links with PHP, so I need the href change to work in all generated links.
id attributes must be unique. You should convert the value changeMe to a classname for use on multiple elements. Then your existing code should work:
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Optionally, you could add a unique id to the second anchor tag and modify the JavaScript code accordingly.
You cannot use an ID on two different elements in HTML. You need to asign each of those a different ID or the same class instead and then apply your href change on each of the IDs, or the class
IDs should be used once per webpage. Classes can be used more plentifully. Remember your specificity. Use class instead of id: http://jsfiddle.net/PtNfD/115/
Yahoo
Not working
$(document).ready (function () {
$('.changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});

Rerun a function when user click on any li.eq(i)

I have a loadbar which I want to reload whenever user clicks on my li which is increment from a loop here is the following function that will be reload on li.eq(i)
live code: http://saadee.bl.ee/hm/
function lifeStream(){
var lftanchor = $(".filetree span.file");
var mainDiv = $(".main");
var loadBg = $(".loadBg");
var loadBar = $(".loadBar");
var boxHeight = $(".box1, .box2");
loadBg.show();
loadBar.animate({"width":"100%"},1500);
loadBg.hide();
boxHeight.show();
boxHeight.delay(1500).animate({"height":"0%"},300);
loadBar.animate({"width":"0%"},0);
}
Use on() like,
$(function(){
$('li').on('click',function(){
lifeStream();
});
});
You can simply handle the click event for the li that matches Your condition.
Considering i is defined, You can do:
jQuery('li').eq(i).click(function() {
lifeStream();
});

Detect anchor is leading to an active window.location

Having such an html:
<a class="someclass" href="some/url/absolute/or/relative">Blah</a>
... along with such javascript:
$("a.someclass").onclick(function() {
var link = $(this).attr("href");
if (link == window.location) // <<<<<<<<<<<<
doSomethingSpecial();
else
doOtherThing();
return false;
});
this code obviously doesn't work.
How to reliably detect that some anchor is leading to the current browser location?
Here are some notes:
Anchor's href could be either absolute or relative.
the fragments of the URLs should be ignored.
The problem is that $('a').attr('href') always returns the relative path. You need to use the native obj.href attribute to get the absolute path, strip hashes and then compare:
var clean = function(str) {
return str.replace(/(\#.*)/,'').toLowerCase();
}
$("a.someclass").click(function(e) {
if (clean(this.href) == clean(window.location)) {
// the link destination is equal to window.location (excluding hashes)
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
EDIT:
If you want to compare pathnames, you can grab it directly from the anchor element:
$("a.someclass").click(function(e) {
if (this.pathname == window.location.pathnname) {
doSomethingSpecial();
} else {
doOtherThing();
}
e.preventDefault();
});
AFAIK, you cannot detect that. Because I can write onclick event handler and then write the code that leads to the current location itself. In this case you can't really depend n the href attribute.
function ReloadWin()
{
window.location.reload();
}
Click me to reload
try this:
$(document).ready(function(){
$("a.someclass").click(function(){
//convert both to lower case
var h=$(this).attr("href").toLowerCase();
var l=window.location.href.toLowerCase();
//if has hash tag remove portion after if
if(l.indexOf("?")>0)
l=l.substring(0,l.indexOf("?"));
if(l.indexOf("#")>0)
l=l.substring(0,l.indexOf("#"));
if(l.length > h.length)
l = l.substring(l.length - h.length);
if(l==h){
alert("On same page");
}else{
alert("Other page");
}
return false;
});
});

Categories

Resources