External dependency clashing with preventDefault()? - javascript

Take a look at the following JavaScript for me that opens a pop up window, please:
function openPopup(e) {
e.preventDefault();
window.open(this.href, "popupWindow", "width=600,height=600,scrollbars=yes");
}
var el = document.querySelector(".bbc-popup");
el.addEventListener("click", openPopup);
Here is a JSFiddle of it in action:
http://jsfiddle.net/dvadcgps/1/
However, when I include it on my page, the code doesn't work, and the link opens in the current tab. The only external JavaScript resources I rely on are jQuery (1.11.3) and Bootstrap 3, and those are both included within the above fiddle, to no effect.
What other reasons could there be for this code to not work?
Here is the full HTML code of the page, with all external resources included, for you to see how it stops working... the links that should open popups are behind the View Chairs' Builds button:
http://jsfiddle.net/e60y004n/1/

Working off Brian Ray's comment, I had to ensure the Event Listener was added to every element, as my current code was only adding it to the first.
Firstly, I add all the elements I want to be targeted to an array.
var chairPopup = document.getElementsByClassName("chair-popup");
I then loop through every element in that array, adding the Event Listener to each:
for (var i = 0; i < chairPopup.length; i++) {
chairPopup[i].addEventListener("click", openPopup);
}
The full code, with the function(), reads as follows:
var chairPopup = document.getElementsByClassName("chair-popup");
function openPopup(e) {
e.preventDefault();
window.open(this.href, "popupWindow", "width=300,height=1000,scrollbars=yes");
}
for (var i = 0; i < chairPopup.length; i++) {
chairPopup[i].addEventListener("click", openPopup);
}
In an answer that has since been deleted by it's author, they mentioned a need to change popupWindow to _blank within the window.open() function. I can confirm that this is needed, otherwise each link opens up in the same popup window.
window.open(this.href, "_blank", "width=300,height=1000,scrollbars=yes");

Related

JavaScript only being called once in Squarespace

I have some custom JavaScript on my SquareSpace site that manipulates Product titles beyond what you can do with SquareSpace's default style editor. It works when initially loading the page (https://www.manilva.co/catalogue-accessories/) but if you click on any of the categories on the left, the styling resets to the default.
I'm assuming the JavaScript is being overwritten by the SquareSpace style, but I can't figure out why. Perhaps I'm calling the function in the wrong place?
Any suggestions would be helpful.
Thanks!
Current code:
document.querySelectorAll(".ProductList-filter-list-item-link".forEach(i=>i.addEventListener("click", function()
{
var prodList = document.querySelectorAll("h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
var text = prodList[i].innerText;
var index = text.indexOf('-');
var lower = text.substring(0, index);
var higher = text.substring(index + 2);
prodList[i].innerHTML = lower.bold() + "<br>" + higher;
});
The source of your problem is that your template has AJAX loading enabled. There are currently a couple generally-accepted ways to deal with this as a Squarespace developer:
Disable AJAX loading
Write your javascript functions in a
manner that will run on initial site load and whenever an "AJAX load" takes place.
Option 1 - Disable AJAX:
In the Home Menu, click Design, and then click Site Styles.
Scroll down to Site: Loading.
Uncheck Enable Ajax Loading.
Option 2 - Account for AJAX in Your JS
There are a number of ways that developers approach this, including the following, added via sitewide code injection:
<script>
window.Squarespace.onInitialize(Y, function() {
// do stuff
});
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// myFunction2(); , etc...
// Reinit. the fn on each new AJAX-loaded page.
window.addEventListener("mercury:load", myFunction);
})();
</script>
or
<script>
(function() {
// Establish a function that does stuff.
var myFunction = function() {
// Do stuff here.
};
// Initialize the fn on site load.
myFunction();
// Reinit. the fn on each new AJAX-loaded page.
new MutationObserver(function() {
myFunction();
// myFunction2(); , etc...
}).observe(document.body, {attributes:true, attributeFilter:["id"]});
})();
</script>
Each of those works for most of the latest (at time of writing) templates most of the time. Each of those have their advantages and disadvantages, and contexts where they do not work as one might expect (for example, on the /cart/ page or other "system" pages). By adding your code within the context of one of the methods above, and ensuring that the code is of course working in the desired contexts and without its own bugs/issues, you will have your code run on initial site load and on each AJAX page load (with some exceptions, depending on the method you use).
Your problem is the page does not reload when clicking a button on the left, just some elements are removed, added and replaced. The changed elements will not be restyled. You will need to re-run your JavaScript after one of those buttons is clicked. Perhaps something like this:
document.querySelectorAll(
".ProductList-filter-list-item"
).forEach(
i=>i.addEventListener(
"click", ()=>console.log("hello")
)
)
where you replace console.log("hello") with whatever resets your formatting.

Open links in another window with javascript

Let's say I have a single HTML page and it contains hundreds of links. These links will load in the same window when anybody clicks them.
I want it to open in another window. I know that I can use target for each link:
My Text1
My Text2
My Text3
Howeder, I'd prefer to use JavaScript if that's possible. Is it possible to do that with JavaScript, and if so, how?
Yes, it is. Use something like this:
var newtab = window.open('http://www.example1.com/', '_blank');
newtab.focus();
This may open in new tabs or new windows depending on the particular browser, but I don't know of a way to control that any more specifically.
EDIT
Or were you asking for a way to set the behavior for all links on the page? Then you can add the proper target to all of them when the page loads.
With jQuery: http://jsfiddle.net/b8hdv/
$(document).ready(function() {
$('a').attr('target', '_blank');
});
...or without jQuery: http://jsfiddle.net/uFvUS/
window.onload = function(e) {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].target = '_blank';
}
}
function open_in_new_tab(url )
{
var win=window.open(url, '_blank');
win.focus();
}
Use like this:
$("#a_id").on("click", function(){
open_in_new_tab($(this).attr("href"));
});
Demo HTML:
Click me!
Found here
Try this:
window.open('http://www.example1.com');
and capture the event click.

How to make a link open multiple pages when clicked

I have two (or more) links. For example: http://google.com and http://yahoo.com.
How can I make them both open when I click on a single link?
For example, a link entitled "click here" which, when clicked, will open two different blank windows.
HTML:
Click Here
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
I did it in a simple way:
<a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>
It'll open runningrss in a new window and virtual-doctor in same window.
You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:
HTML
<ul class="yourlinks">
<li><a href="http://www.google.com/"></li>
<li><a href="http://www.yahoo.com/"></li>
</ul>
jQuery
$(function() { // On DOM content ready...
var urls = [];
$('.yourlinks a').each(function() {
urls.push(this.href); // Store the URLs from the links...
});
var multilink = $('Click here'); // Create a new link...
multilink.click(function() {
for (var i in urls) {
window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
}
});
$('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});
This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)
You can open multiple windows on single click... Try this..
<a href="http://--"
onclick=" window.open('http://--','','width=700,height=700');
window.open('http://--','','width=700,height=500'); ..// add more"
>Click Here</a>`
You need to unblock the pop up windows for your browser and the code could work.
chrome://settings/contentExceptions#popups
I created a bit of a hybrid approach between Paul & Adam's approach:
The link that opens the array of links is already in the html. The jquery just creates the array of links and opens each one when the "open-all" button is clicked:
HTML:
<ul class="links">
<li></li>
<li></li>
</ul>
<a id="open-all" href="#">OPEN ALL</a>
JQUERY:
$(function() { // On DOM content ready...
var hrefs = [];
$('.links a').each(function() {
hrefs.push(this.href); // Store the URLs from the links...
});
$('#open-all').click(function() {
for (var i in hrefs) {
window.open(hrefs[i]); // ...that opens each stored link in its own window when clicked...
}
});
});
You can check it out here:
https://jsfiddle.net/daveaseeman/vonob51n/1/
Here is a basic implementation in javascript - I separated it into an external file
HTML
Click To Open Links
JS
var myLinks = [
"https://google.com",
"https://www.w3schools.com/jsref/met_win_open.asp",
"https://developer.mozilla.org/en-US/docs/Web/API/Window/open"
]
function openMultipleLinks(links) {
for (var i = 0; i < links.length; i ++) {
window.open(links[i]);
}
}
Note that the user will have to enable pop-ups for the pages to open.
Here it is in action: https://jsfiddle.net/cuppajoeman/rjavuhcg/
If you prefer to inform the visitor which links will be opened, you can use a JS function reading links from an html element. You can even let the visitor write/modify the links as seen below:
<script type="text/javascript">
function open_all_links() {
var x = document.getElementById('my_urls').value.split('\n');
for (var i = 0; i < x.length; i++)
if (x[i].indexOf('.') > 0)
if (x[i].indexOf('://') < 0)
window.open('http://' + x[i]);
else
window.open(x[i]);
}
</script>
<form method="post" name="input" action="">
<textarea id="my_urls" rows="4" placeholder="enter links in each row..."></textarea>
<input value="open all now" type="button" onclick="open_all_links();">
</form>

Change link targets

Is there a way (I assume it would be with javascript) that I can have a checkbox or link on my page that will make all the links on my page have target="_blank"?
I want to have a checkbox that says something like "Open all links in new page/tab" on my site that when checked will change the target and unchecked will put it back to how it was.
jQuery example
$(function() {
$('#yourCheckoxId').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
You might want to try jQuery as an alternative to genuine Javascript
the actual code could look something like that:
$('a').attr(target, '_blank')
Modifying the target attribute of all the anchors on the page is merely a matter of getting all links, and setting their target properties one by one:
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
anchors[i].target = '_blank';
}

Disabling a link tag using JavaScript on my printable page

I have a script that creates a printable page by copying the HTML across and then doing some manipulation, such as disabling the buttons on the page, on page load.
I also want to disable the links on the page. I don't really mind if they look like links still as long as they don't do anything, and don't give any JavaScript errors!
The anchor tag doesn't seem to have a disabled attribute...
Unfortunately, I can't use jQuery, so JavaScript only please!
Edit: I want to disable the links, buttons etc on the page so that when the 'printable page' opens in another window, the user cannot mess with it by clicking buttons or links. I want it to essentially be a 'frozen snapshot' of the page that they want to print.
Setting their href to # and overwriting the onclick event should do the trick.
var links = document.getElementsByTagName("A"), j;
for (j = 0;j < links.length; j += 1) {
links[j].href = '#';
links[j].onclick = function () {
return false;
};
}
Why can't you use jQuery? So much nicer...
$('a').each(function(){this.onclick=function(){return false}});
Anyway here is a normal javascript way. Smaller than above and you also don't need to modify the links... by defining the onclick function to return false it will not visit the href:
var anchors = document.getElementsByTagName("a");
for (i = 0; i < anchors.length; i++)
anchors[i].onclick = function(){return false};
There is also an array of links in the document object. While I've never tried, I believe you can set them too.
for (i=0;i<document.links.length;i+=1) {
document.links[i]=='#';
}

Categories