Get Href Link; if JPG to skip - javascript

I've created a loader for my website (the whole front end is custom,so as of right now i can edit about 95% of everything I have except for woocommerce plugin).
Super simple one, it follows this logic, if the anchor is an # or the page itself it wont do anything (which is what I wanted) but the woocommerce plugin to generate my image gallery is a link that isn't the page itself or a #. Which means I need to collect the path-name of the extension that if it ends on jpg png or any image file to continue; and skip over the rest of the animation and allow the plugin to run its course.
Ive use Barba JS, SWUP and other animations with woocommerce and this is the only one that doesnt interrupt or have so many conditions with woocommerce.
function fadeInPage() {
if (!window.AnimationEvent) { return; }
var fader = document.getElementById('fader');
fader.classList.add('fade-out');
}
document.addEventListener('DOMContentLoaded', function() {
if (!window.AnimationEvent) { return }
var anchors = document.getElementsByTagName('a');
******* for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].hostname !== window.location.hostname || anchors[idx].pathname === window.location.pathname) *******
{
continue;
}
anchors[idx].addEventListener('click', function(event) {
var fader = document.getElementById('fader'),
anchor = event.currentTarget;
var listener = function() {
window.location = anchor.href;
fader.removeEventListener('animationend', listener);
};
fader.addEventListener('animationend', listener);
event.preventDefault();
fader.classList.add('fade-in');
});
}
});
window.addEventListener('pageshow', function (event) {
if (!event.persisted) {
return;
}
var fader = document.getElementById('fader');
fader.classList.remove('fade-in');
});
I starred what i need changed. the animation works, the page transition works. I need the animation to recognize if the a tag ends with an jpg or png to skip and not do the animation and treat the link as if the animation wasn't there.

Never used woocommerce so I don't totally understand the use case, but you can get the file extension of a link like so:
for (var idx = 0; idx < anchors.length; idx += 1) {
let fileType = anchors[idx].href.split('.').pop();
//Do whatever
}
Or if you want to compare it to a preset list of extensions you can use a regex:
for (var idx = 0; idx < anchors.length; idx += 1) {
if (anchors[idx].href.match(/\.(jpg|png)$/)) {
//Do whatever
}
}

Related

button to jump to next anchor

I have a wordpress-website with section scrolling enabled and added 2 buttons that should jump to the previous or the next page on the website and 2 buttons that should jump to the previous or next chapter on the website.
based on this post Goto Next Anchor Button I added the script but the browser returns the length = 0 for anchors, document.getElementByTagName() returns an array that is to big
and document.getElementByName() didn't work too.
var anchordivs = document.querySelectorAll('[data-anchor][data-id]');
var anchors = anchordivs.length;
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName = 0;
var anchorName = window.location.hash.replace(/#/,'');
if (anchorName){
for (var i=0, iLength=anchordivs.length; i<iLength; i++) {
if (anchordivs[i].dataset.anchor == anchorName) {
nextAnchorName = anchordivs[i+1 % iLength].dataset.anchor;
break;
}
}
}
if (!nextAnchorName){
nextAnchorName=anchordivs[0].dataset.anchor;
}
window.location.href = loc + '#' + nextAnchorName;
}
On button click the site should scroll to the next section of the website.
EDIT: wordpress did create the anchors as data-anchors in the respective divs:
<div ... data-anchor="c_home">. Here is what still does not work. On clicking the button the site does not jump to the new anchor and manually entering a anchor in the adressline of the browser does not work either. The JS-Code is tested and works now.
Maybe the problem for the missing jump is that it is all on one page?
I got it working by changing the last codeline to the following:
location.href ='#' + nextAnchorName;
location.reload();
Now its reloading the site with each click, but it works. That is not what i want.
I changed var anchors = document.body.getElementsByTagName("a"); and nextAnchorName = anchors[i++ % iLen].name;
function goToNextAnchor() {
var anchors = document.body.getElementsByTagName("a");
var loc = window.location.href.replace(/#.*/,'');
var nextAnchorName;
// Get name of the current anchor from the hash
// if there is one
var anchorName = window.location.hash.replace(/#/,'');
// If there is an anchor name...
if (anchorName) {
// Find current element in anchor list, then
// get next anchor name, or if at last anchor, set to first
for (var i=0, iLen=anchors.length; i<iLen; i++) {
if (anchors[i].name == anchorName) {
nextAnchorName = anchors[i++ % iLen].name;
break;
}
}
}
// If there was no anchorName or no match,
// set nextAnchorName to first anchor name
if (!nextAnchorName) {
nextAnchorName = anchors[0].name;
}
// Go to new URL
window.location.href = loc + '#' + nextAnchorName;
}

`How to change between list view and grid view and also keep the current state after page refresh

I need to toggle between list view and grid view which i was able to do using js to change the css but the problem is if a user refresh the page the default view is restored, how can I make this, probably append the view name to the url so that the current view will remain after user refresh page. example having the following URl www.example.com/item/search?q=myquery&style=list, www.example.com/item/search?q=myquery&style=grid, or is there a better way to do this. below is a fiddle of my code and any refresh will return the view to grid even when i select list view
JS FIDDLE
Note: I'm using yii2 framework so regarding the url formation i'm open to both php and JS solution, thanks in advance
$(".listView").on('click', function() {
listView();
});
$(".gridView").on('click', function() {
gridView();
});
// Get the elements with class="column"
var elements = document.getElementsByClassName("column");
// Declare a loop variable
var i;
// List View
function listView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "100%";
}
}
// Grid View
function gridView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "50%";
}
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
In order to do what you want, actually you dun need to do any work on backend but simply using the cookie.
You may improve it, I just provide a picture.
$(".listView").on('click', function() {
listView();
setCookie('list');
});
$(".gridView").on('click', function() {
gridView();
setCookie('grid');
});
function setCookie(name) {
document.cookie = name;
}
And when you start the JS, check the cookie first by
var x = document.cookie;
if (x == 'list'){...}
else if (x == 'grid'){...}
You may also choose to use localStorage, the technical is the same. However, only when if you list and grid data has no difference, and no server data is further required.
I think MatrixTai has the right idea, but I personally prefer usually localStorage.
Here is an example with a functions for getting/setting the view:
$(".listView").on('click', function() {
listView();
setView('list');
});
$(".gridView").on('click', function() {
gridView();
setView('grid');
});
function setView(view) {
localStorage.setItem('view', view);
}
function getView(view) {
return localStorage.getItem('view');
}

Set css of multiple divs with same id

I have a reveal presentation in an iframe. Each slide has a div with an audio player in in and the divs id is "narration".
I have a button outside the frame that is used to hide/show this div. The problem is that it only does this for the first slide and not the rest.
EDIT : This seems to hide the divs :
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
HTML in iframe (There is one for each slide) :
<div id="narration"><p align="middle">
<audio controls="" preload="none">
<source src="mp3/2.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio></p>
</div>
JS (outside of iframe):
function checkAudio() {
if (document.getElementById('cb1').checked) {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'none';
} else {
document.getElementById('ppt').contentWindow.document.getElementById('narration').style.display = 'block';
}
}
After changing your IDs to classes (read here why), you need to update your javascript code to handle the multiple divs via a foreach loop.
function checkAudio() {
var narrationDivs = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var newDisplay = "block";
if (document.getElementById('cb1').checked) {
newDisplay = "none";
}
narrationDivs.forEach(function(div) {
div.style.display = newDisplay;
});
}
In order to have the code run again when your iframe changes, you need to update your iframe changing function:
function setURL(url){
document.getElementById('ppt').src = url;
checkAudio(); // Just run the function again!
}
If you want to show a specific element using a button, you should use a specific ID. If you want to show all items using a single button you should use classes. You could also use classes to show a specific element e.g.: The 5th button will show the 5th element but this is not a good style.
When the site in the iframe loads the next frame, your code doesn't know to hide the div it presents again. You need an event to process on.
You need to poll the id so that if it shows up again, you can hide it. See: iframe contents change event?
function checkAudio() {
if (document.getElementById('cb1').checked) {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'none';
}
} else {
var y = document.getElementById('ppt').contentWindow.document.getElementsByClassName('narration');
var i;
for (i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
You might also want to check out the audio-slideshow plugin that allows to play separate audio files for each slide and fragment. If your main need is this, the plugin should do the job for you.
You can find a demo here and the plugin here. There is also the slideshow-recorder plugin that allows you to record your narration.
Asvin

codemirror - detect and create links inside editor

I am using codemirror, configured to display javascript.
I have code like this:
...
var ref = 'http://www.example.com/test.html';
var ref2 = 'http://www.example.com/test2.html';
...
When displaying the editor it would be great if I could click on the links that might be present in the editor. The link would open the page on a different tab obviously.
is there an easy way to achieve this ?
Not really easy, but what you'd do is:
Write an overlay mode that recognizes such links. Basically, this is a mode that spits out a custom token type when it finds something that looks like a link, and null otherwise. You can use the simple mode addon to make this easier. You can use this token type's CSS class (for example "link" becomes cm-link) to style your links.
Make your editor use your overlay by calling the addOverlay method.
Register a mousedown event handler on your editor (instance.getWrapperElement().addEventListener(...)).
In this handler, check whether the event's target has the link CSS class. If it does, the user is clicking a link.
If so, use the coordsChar method, using the coordinates from your mouse event, to find the position in the document that was clicked. Extract the actual link from the document text around that position, and follow it.
(Or, even better, instead of directly interfering with the click, which might be intended to put the cursor in the link or select it, show a widget containing a regular link whenever the cursor is inside of link text.)
Here is a solution I came up with:
demo here: plunkr
code:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.17.0/codemirror.css"/>
<style>
html, body { height:100%; }
.CodeMirror .cm-url { color: blue; }
</style>
</head>
<body>
<script>
var cm = CodeMirror(document.body);
cm.setValue('hover over the links below\nlink1 https://plnkr.co/edit/5m31E14HUEhSXrXtOkNJ some text\nlink2 google.com\n');
hyperlinkOverlay(cm);
function hoverWidgetOnOverlay(cm, overlayClass, widget) {
cm.addWidget({line:0, ch:0}, widget, true);
widget.style.position = 'fixed';
widget.style.zIndex=100000;
widget.style.top=widget.style.left='-1000px'; // hide it
widget.dataset.token=null;
cm.getWrapperElement().addEventListener('mousemove', e => {
let onToken=e.target.classList.contains("cm-"+overlayClass), onWidget=(e.target===widget || widget.contains(e.target));
if (onToken && e.target.innerText!==widget.dataset.token) { // entered token, show widget
var rect = e.target.getBoundingClientRect();
widget.style.left=rect.left+'px';
widget.style.top=rect.bottom+'px';
//let charCoords=cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY }));
//widget.style.left=(e.pageX-5)+'px';
//widget.style.top=(cm.charCoords(cm.coordsChar({ left: e.pageX, top:e.pageY })).bottom-1)+'px';
widget.dataset.token=e.target.innerText;
if (typeof widget.onShown==='function') widget.onShown();
} else if ((e.target===widget || widget.contains(e.target))) { // entered widget, call widget.onEntered
if (widget.dataset.entered==='true' && typeof widget.onEntered==='function') widget.onEntered();
widget.dataset.entered='true';
} else if (!onToken && widget.style.left!=='-1000px') { // we stepped outside
widget.style.top=widget.style.left='-1000px'; // hide it
delete widget.dataset.token;
widget.dataset.entered='false';
if (typeof widget.onHidden==='function') widget.onHidden();
}
return true;
});
}
function hyperlinkOverlay(cm) {
if (!cm) return;
const rx_word = "\" "; // Define what separates a word
function isUrl(s) {
if (!isUrl.rx_url) {
// taken from https://gist.github.com/dperini/729294
isUrl.rx_url=/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
// valid prefixes
isUrl.prefixes=['http:\/\/', 'https:\/\/', 'ftp:\/\/', 'www.'];
// taken from https://w3techs.com/technologies/overview/top_level_domain/all
isUrl.domains=['com','ru','net','org','de','jp','uk','br','pl','in','it','fr','au','info','nl','ir','cn','es','cz','kr','ua','ca','eu','biz','za','gr','co','ro','se','tw','mx','vn','tr','ch','hu','at','be','dk','tv','me','ar','no','us','sk','xyz','fi','id','cl','by','nz','il','ie','pt','kz','io','my','lt','hk','cc','sg','edu','pk','su','bg','th','top','lv','hr','pe','club','rs','ae','az','si','ph','pro','ng','tk','ee','asia','mobi'];
}
if (!isUrl.rx_url.test(s)) return false;
for (let i=0; i<isUrl.prefixes.length; i++) if (s.startsWith(isUrl.prefixes[i])) return true;
for (let i=0; i<isUrl.domains.length; i++) if (s.endsWith('.'+isUrl.domains[i]) || s.includes('.'+isUrl.domains[i]+'\/') ||s.includes('.'+isUrl.domains[i]+'?')) return true;
return false;
}
cm.addOverlay({
token: function(stream) {
let ch = stream.peek();
let word = "";
if (rx_word.includes(ch) || ch==='\uE000' || ch==='\uE001') {
stream.next();
return null;
}
while ((ch = stream.peek()) && !rx_word.includes(ch)) {
word += ch;
stream.next();
}
if (isUrl(word)) return "url"; // CSS class: cm-url
}},
{ opaque : true } // opaque will remove any spelling overlay etc
);
let widget=document.createElement('button');
widget.innerHTML='→'
widget.onclick=function(e) {
if (!widget.dataset.token) return;
let link=widget.dataset.token;
if (!(new RegExp('^(?:(?:https?|ftp):\/\/)', 'i')).test(link)) link="http:\/\/"+link;
window.open(link, '_blank');
return true;
};
hoverWidgetOnOverlay(cm, 'url', widget);
}
</script>
</body>
</html>
Here is a starting point, but it need to be improved.
LIVE DEMO
function makeHyperLink(innerTextInside)
{
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
if(all[i].innerText == innerTextInside)
{
all[i].innerHTML="<a target='_blank' href='https://google.com'>THIS IS A LINK TO GOOGLE</a>"
}
}
}

Stop javascript redirection on href="javascript:void"

I've been using a script which prefixes redirect.php on "onmouseevent" triggers. But I don't want it on certain sites, like google etc. Please see the code below:
var matchavailable = 0;
var disallowinks = "google,microsoft,yahoo";
$n("a").mousedown(function () {
var linkArray = disallowlinks.split(',');
for (var i = 0; i < linkArray.length; i++) {
if ($n(this).attr('href').indexOf(linkArray[i]) > 0) {
matchavailable = 1;
break;
}
else {
matchavailable = 0;
}
}
if (matchavailable == 0) {
if ($n(this).hasClass('linked')) {
}
else
{
$n(this).attr('href', "http://yoursite.com/redirect.php?q=" + encodeURIComponent($n(this).attr('href')));
$n(this).attr('target', '_blank');
$n(this).addClass("linked");
}
}
});
The javascript runs so far so good on all anchor tags. Just that, I have a popup which I show on my website and when I try to close the popup (X marks the spot), the redirect.php gets prefixed on that as well.
So my question is, how do we disallow the script to NOT run on anchor tags with the value starting with "javascript" ?
For example, i don't want it to run on:
<a href="javascript:void"> or <a href="any random parameter">
How do I go about this? WOuld be great to get some help

Categories

Resources