I want to be able to focus the original page after opening a new window/tab, the same way as it's done on this website: http://www.vouchercodes.co.uk/laredoute.co.uk
Its when you click on the green button 'Get code and open site'.
the code is all there for you to see. I used firebug to find the <a> object that had the click event bound to the code that did the popup behind the main browser window. I scrolled down to look inside the global.js file and found this:
Basically the .blur() on the named popup window will pass focus back to the main window for browsers that support it and return false; will ensure the link doesn't open in the current window which is the default behaviour. Scroll down the code below and you'll see it towards the bottom.
// -- VoucherClick --
// This baby does the funky stuff when the user clicks to reveal the voucher code
(function($) {
$.fn.extend({
voucherClick: function(config) {
return this.each(function() {
// What is the objects parent?
var theObject = $(this);
if ($(this).hasClass('the-image')) {
var theParent = theObject.parent().parent();
} else {
var theParent = theObject.parent().parent().parent();
}
theObject.click(function() {
// Revealed codes have a light yellow background
// First we remove the background of any currently selected vouchers
$('.selected-voucher').css('backgroundColor','#fff').removeClass('selected-voucher');
// Now we add the yellow background. We have to check what was clicked as it affects
// how far up the DOM tree the voucher DIV starts
// We also must check if we are on an indiviual page with an expired voucher,
// because the yellow background can overlap the left hand edge of the voucher
if (theParent.parent().hasClass('individual-expired')) {
} else {
theParent.css('backgroundColor','#ffffee').addClass('selected-voucher');
}
// Check to see if the voucher has alread been revealed - we only want to run this
// if it hasn't yet been clicked
if (!theParent.data('voucherRevealed')) {
// Make a note that this voucher has been clicked
theParent.data('voucherRevealed', true)
// Make a note of the voucher code and create the revealed code module
var thisCode = theParent.find('strong').html();
// If the code is over 18 characters, we need to reduce the font size
if (thisCode.length > 8) {
thisCode = '<span class="revealedVoucherCode small">' + thisCode + '</span>';
} else {
thisCode = '<span class="revealedVoucherCode">' + thisCode + '</span>';
}
// Fade out the initial module and fade in the revealed voucher module
theParent.find('.code-wrapper').fadeOut('normal', function() {
// If it's an individual page there is no H3
if (theParent.find('h3').length == 0){
// So we add the revealed module after the dates
theParent.find('.dates').after('<div class="revealedVoucher">' + thisCode + '</div>');
} else {
theParent.find('h3').after('<div class="revealedVoucher">' + thisCode + '</div>');
}
theParent.find('.revealedVoucher').fadeIn();
})
}
// Open the merchant link in a new window
var mer_window = window.open(theObject.attr('href'), '_blank', 'toolbar=1,location=1,directories=1,scrollbars=1,resizable=1,status=1,menubar=1');
// Where browsers support it, let's pop this new window BEHIND the current window
if (typeof mer_window === "object") {
mer_window.blur();
}
// Reveal the What Just Happened Text, which was set up in the VoucherInit function
theParent.find('.what-just-happened').slideDown();
// Don't open the link in this current window
return false;
}); // end theObject click function
}) // end this.each function
} // end function(config)
}) // end $.fn.extend
}) (jQuery);
based on the above example, I've put together the following code, however click event doesn't work...
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.extend({
myClick: function(config) {
return this.each(function() {
var theObject = $(this);
theObject.click(function() {
var new_window = window.open(theObject.attr('href'), '_blank', 'toolbar=1,location=1,directories=1,scrollbars=1,resizable=1,status=1,menubar=1');
if (typeof new_window === "object") {
new_window.blur();
}
return false;
});
})
}
})
}) (jQuery);
$('.fade').myClick();
</script>
</head>
<body>
Google<br />
</body>
</html>
Related
Hash anchor links fail to find/target ID DOM element target (and therefore fail to trigger JS UI tab change)
Hi visit https://eurosurveillance.org/content/10.2807/1560-7917.ES.2019.24.40.1900157 and scroll down the HTML fulltext (shown in this tab) and try clicking on the link marked 'Supplement 1' or 'Supplement 2' note nothing happens.
There is nothing clever about the links they are normal html hash links....
Supplement 1
Now if you visit the same page but this time do a hard reload with the following URL in the browser address bar https://eurosurveillance.org/content/10.2807/1560-7917.ES.2019.24.40.1900157#html_fulltext (notice the only change is the hash in the URL). Now try following the same instructions as before and you will notice that for some reason the anchor link is now followed and the anchor tab JS is triggered this is behaviour that I am expecting
Please advise. thanks in advance.
Hi many thanks the issue was resolved by refactoring the responsive-tabs.js code:
$(document).ready(function() {
//responsive tabs API code.
var Tabs = {
init: function() {
this.bindUIfunctions();
this.pageLoadCorrectTab();
},
bindUIfunctions: function() {
// Delegation
$(document)
.on("click", ".js-transformer-tabs a[href^='#']:not('.active, .disabled')", function(event) {
Tabs.changeTab(this.hash);
event.preventDefault();
})
.on("click", ".js-transformer-tabs a.active, .js-transformer-tabs a.disabled", function(event) {
Tabs.toggleMobileMenu(event, this);
event.preventDefault();
})
.on("click", ".js-textoptionsFulltext a.html:not('.disabled')", function(event) {
//console.log("tab?" + this.hash);
event.preventBubble=true;
var anchorTab = Tabs.changeTab(this.hash);
anchorTab.trigger("click"); //trigger click event in this case it will be html fulltext.
//event.preventDefault();
});
//We also need to handle the back state by telling the browser to trigger the tab behaviour!
$(window).on('popstate', function(e) {
anchor = $('[href="' + document.location.hash + '"]');
if (anchor.length > 0) {
Tabs.displayTab(anchor);
} else {
var defaultAnchor = $('.js-transformer-tabs li.active a');
if (defaultAnchor) {
Tabs.displayTab(defaultAnchor)
}
}
});
},
changeTab: function(hash) {
var anchor = $(".js-transformer-tabs a[href='" + hash + "']");
var activeTab = anchor.find('span strong');
Tabs.displayTab(anchor);
$(".js-dropdown li").hide();
$(".js-mobile-tab").text($(activeTab).text());
// update history stack adding additional history entries.
// pushState is supported!
history.pushState(null, null, hash);
// Close menu, in case mobile
return anchor; // make property available outside the function
},
pageLoadCorrectTab: function() {
//console.log("document.location.hash: " + document.location.hash);
if (document.location.hash.length > 0) {
// If the page has a hash on load, go to that tab
var anchor = $(".js-transformer-tabs a[href='" + document.location.hash + "']");
if (!anchor.hasClass("disabled")) {
var anchorTab = this.changeTab(document.location.hash);
// this is a further amendment to allow the fulltext and
//(any future event if its attached) to load when bookmarking a page with a particular tab.
anchorTab.trigger("click");
}
} else if ($(".js-transformer-tabs .active.tabIcon .active").length > 0) {
// go to which ever tab is defined as active in the JSP page and trigger a click on it
// but, only when no hash in the url
var activeTab = $(".js-transformer-tabs .active.tabIcon .active");
activeTab.trigger("click"); //trigger click
}
},
toggleMobileMenu: function(event, el) {
$(el).closest("ul").toggleClass("open");
},
displayTab: function(anchortab) {
var url = anchortab.attr("href");
//console.log("url" + url);
var divtabContent = $(url);
// activate correct anchor (visually)
anchortab.addClass("active").parent().siblings().find("a").removeClass("active");
// activate correct div (visually)
divtabContent.addClass("active").siblings().removeClass("active");
}
}
Modernizr.load([{
//test
test : Modernizr.history,
//if yes then do nothing as nothing extra needs loading....
//if no then we need to load the history API via AJAX
nope : ['/js/' + ingentaCMSApp.instanceprefix + '/vendor/history.min.js'],
complete : function() {
var location = window.history.location || window.location;
Tabs.init();
}
}])
});
//end of responsive tabs API code.
$(".js-select").click(function(){
$(".js-dropdown li").slideToggle();
});
I am doing one feature about showing alert on external link(apart from current domain) click. For that, I have written below code. All is working fine except below scenario.
$('a').each(function() {
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.click(function(event) {
//console.log($a.get(0));
//var myClasses = this.classList;
//console.log(myClasses.length + " " + myClasses['0']);
$("#redirectconfirm-modal").removeClass('hide');
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
$modal.on('show', function() {
$modal.find('.btn-continue').click(function() {
confirmed = true;
$a.get(0).click();
$modal.modal('hide');
location.reload();
});
});
$modal.on('hide', function() {
$a.get(0).removeClass("selected");
confirmed = false;
});
$modal.modal('show');
}
});
}
});
Scenario which produces this issue:
Click on any external link from the site, it open a modal popup for redirection confirmation with continue & return button.
If I click on "Return" button it closes the modal popup.
Now, I am clicking on external link from my site, it open the modal again but this time I am clicking on "Continue" button & guess what, it open that external link in 3 different tabs
Actually on each anchor tag click, it saves whole anchor tag value. I think, if remove all these anchor tag values on modal close code i.e. $modal.on('hide', function() { }) it will resolve problem. I had tried with many different ways but still facing this issue.
Can you please provide solution/suggestion on that?
Problem is when you have 3 external links (as you probably have), than you set 3 times this part of code:
$modal.on('show', function() { ... });
$modal.on('hide', function() { ... });
which is wrong. Those events listeners should be set only once.
Some simplified code would look like this:
var $modal = $("#redirectconfirm-modal");
var currentDomain = 'blabla';
$modal.on('click', '.btn-continue', function(e) {
window.location = $modal.data('redirectTo');
});
$('a').each(function() {
var $a = jQuery(this);
if( $a.get(0).hostname && getDomain($a.get(0).hostname)!=currentDomain ) {
$a.click(function(e) {
$modal.data('redirectTo', $a.attr('href'));
$modal.modal('show');
});
};
});
Don't inline your events, you may try something like this:
$('a').each(function() { //add a class to all external links
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.addClass('modalOpen');
}
});
$('.modalOpen').not(".selected").click(function(event) { //open the modal if you click on a external link
event.preventDefault();
$('.modalOpen').addClass('selected'); //add class selected to it
$modal.modal('show');
});
$modal.on('hide', function() {
$('.selected').removeClass("selected");//remove the class if you close the modal
});
$('.btn-continue').click(function() {
$('.selected').click();//if the users clicks on continue open the external link and hide the modal
$modal.modal('hide');
});
I have an HTML page in which a hidden div becomes visible when a button is clicked. Something like this:
$('#display').click(function(){
$('#itemList').removeClass('hide');
...
})
On another page, there is a link which when clicked takes the user back to the earlier page, and the element with id='itemList' on that page has to become visible. The code is something like this:
<a href='firstHTML.php'> View items</a>
I am not sure what else to add to the code to make the other page appear with the previously hidden element visible. Can somebody help please?
One of the most probable solution is localStorage .Where as you may also implement Cookies or string query to pass value to other page.
I am showing the use of localstorage , you may store the id in localStorage on click of anchor as below
<a href='firstHTML.php' data-showId='itemList'> View items</a>
Now bind event on anchor
$("[data-showId]").bind('click',function(){
var idToShow=$(this).attr('data-showId');
if(idToShow)
store('visibleId', idToShow);
});
Now all you need to define these functions .
function setup() {
var tmp = get('visibleId');
if (tmp)
showDiv(tmp);
}
function showDiv(cls) {
$("#"+cls).removeClass('hide');
}
function get(name) {
if (typeof (Storage) !== "undefined") {
return localStorage.getItem(name);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
function store(name, val) {
if (typeof (Storage) !== "undefined") {
localStorage.setItem(name, val);
} else {
window.alert('Please use a modern browser to properly view this template!');
}
}
Now call setup() on dom ready..
First of all, I would use the jQuery function to hide/show the List instead of using an own CSS class for it:
$('#display').click(function(){
$('#itemList').show();
...
})
Then a possible approach for your problem could be to use a get Parameter for this, for example:
<a href='firstHTML.php?list=show'> View items</a>
And with jQuery
Create a helperfunction (Taken from Get url parameter jquery Or How to Get Query String Values In js):
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}else{
return results[1] || 0;
}
}
Read out the property:
var listStatus = $.urlParam('list');
Unhide the list in case it should be shown:
$( document ).ready(function() {
if(listStatus == 'show') {
$('#itemList').show();
}
});
My client has a link on their website which opens a customer service chat window in a popup. They are seeing users clicking the chat link multiple times, which opens multiple chat sessions, and it is throwing off their stats. I need to disable the link when the chat window is opened, and restore it when the chat window has been closed. I can't modify/access child window.
The original link looks like this:
<a class="initChat" onclick="window.open('https://chatlinkhere.com','chatwindow','width=612,height=380,scrollbars=0'); return false;">
I figured the best thing to do would be to store the window.open() as a variable in a function:
function openChat() {
child = window.open('http://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0,menubar=0');
}
and change the link HTML to
<a class="initChat" onclick="openChat();">
Note: Ideally, I'd like to detect the original onclick's value, and store it in a variable. Something like:
jQuery('.initChat').find().attr('onclick');
But I'm not sure how to store it and then call it later.
Next I need to run a check to see if the chat window is open or not:
timer = setInterval(checkChild, 500);
function checkChild() {
if (child.open) {
alert("opened");
jQuery(".initChat").removeAttr("onclick");
jQuery(".initChat").css("opacity", ".5");
clearInterval(timer);
}
if (child.closed) {
alert("closed");
jQuery(".initChat").attr('onclick', 'openChat(); checkChild();');
jQuery(".initChat").css("opacity", "1.0");
clearInterval(timer);
}
}
Note: the alerts are just there for testing.
And add the new function to the link
<a class="initChat" onclick="openChat(); checkChild();">
And once the chat window is closed, I need to restore the onclick attribute to the link (is there an easier way to do this?)
Fiddle demo is here -> http://jsfiddle.net/JkthJ/
When I check Chrome Console I'm getting error
Uncaught TypeError: Cannot read property 'open' of undefined
UPDATE
Whoever left me the answer in http://jsfiddle.net/JkthJ/2/ thank you very much it works! :)
i think you need is open pop up if already open then foucus on pop up or noyhing should happen
you can rewrite your function as
var winPop = false;
function OpenWindow(url){
if(winPop && !winPop.closed){ //checks to see if window is open
winPop.focus(); // or nothing
}
else{
winPop = window.open(url,"winPop");
}
}
just do it in a simple way. disable the mouse events on anchor link after child window open.
css
.disableEvents{
pointer-events: none;
}
js
var childWindow;
$('a').on('click',function(){
childWindow = window.open('_blank',"height:200","width:500");
$(this).addClass('disableEvents');
});
if (typeof childWindow.attachEvent != "undefined") {
childWindow.attachEvent("onunload", enableEvents);
} else if (typeof childWindow.addEventListener != "undefined") {
childWindow.addEventListener("unload", enableEvents, false);
}
enableEvents = function(){
$('a').removeClass('disableEvents');
};
update
your child window is plain html page. Do the changes in child window html code:
<html>
<head>
<script>
function myFunction()
{
window.opener.enableEvents(); //it calls enableEvents function
}
</script>
</head>
<body onunload="myFunction()">
<!--your content-->
</body>
</html>
This is what I got to finally work:
<a class="initChat" onclick="checkWin()"></a>
<script>
var myWindow;
function openWin() {
myWindow = window.open('https://www.google.com', 'chatwindow', 'width=612,height=380,scrollbars=0');
}
function checkWin() {
if (!myWindow) {
openWin();
} else {
if (myWindow.closed) {
openWin();
} else {
alert('Chat is already opened.');
myWindow.focus();
}
}
}
</script>
I'm not very expert in using javascript and jquery but I'm working with them for a client.
I have encountered a problem using two script: the first one makes a top panel sliding, the second is in a form. This one is used in order to hide or show a particular field basing on the drop down list choice.
I've found that if I disable the first script (the panel), the second script is working fine and vice versa. I tried usign JQuery noConflict() in the head of the page but nothing happened.
Here the code of the first script (sliding panel):
$(document).ready(function () {
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function () {
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
}); // end on DOM
Here the JS code for the form (hide/show field):
$document.addEvent('domready', function () {
$('motivo_contatto').addEvent('change', function () {
if ($('motivo_contatto').value == 'Invia CV') {
$('upload_file').style.visibility = 'visible';
} else {
$('upload_file').style.visibility = 'hidden';
}
});
$('upload_file').style.visibility = 'hidden';
});
});
Can anyone help me ? Thank you and have a nice day!
you're using 2 different ways to add things to happen to the document ready event:
$(document).ready(function(){ ... });
and
$document.addEvent('domready', function() { ... });
maybe if you just use one it works; maybe the code below will work; I put it all in the first option to run code on document ready:
I edited below code and removed all mootools code; so it might work now.
$(document).ready(function(){
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function(){
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
document.getElementById('motivo_contatto').onchange = function() {
if(document.getElementById('motivo_contatto').value == 'Invia CV') {
document.getElementById('upload_file').style.visibility = 'visible';
} else {
document.getElementById('upload_file').style.visibility = 'hidden';
}
};
document.getElementById('upload_file').style.visibility = 'hidden';
}); // end on DOM
Mixing up two different libraries. Not a good idea.
If you want to keep on following on that pattern, wrap one of the function on a different function and call if from another.
Like:
function moo() {
$('motivo_contatto').addEvent('change', function () {
if ($('motivo_contatto').value == 'Invia CV') {
$('upload_file').style.visibility = 'visible';
} else {
$('upload_file').style.visibility = 'hidden';
}
});
$('upload_file').style.visibility = 'hidden';
});
}
Then call it from another
$(document).ready(function () {
moo(); // Call the moo function
// Lets make the top panel toggle based on the click of the show/hide link
$("#sub-panel").click(function () {
// Toggle the bar up
$("#top-panel").slideToggle();
// Settings
var el = $("#shText");
// Lets us know whats inside the element
var state = $("#shText").html();
// Change the state
state = (state == 'Nascondi' ? '<span id="shText">Entra</span>' : '<span id="shText">Nascondi</span>');
// Finally change whats insdide the element ID
el.replaceWith(state);
}); // end sub panel click function
}); // end on DOM
Check this answer, if you want to use both libraries side by side