Modify url based on a click event - javascript

I have a series of divs that when clicked it slides up basically a modal. The modal has a data-attribute that appears in the url. The issue I'm having is when I close the modal, the url still has the data-attribute hash, it doesn't revert back and I need it to.
This is the js:
$('[data-agent]').click(function() {
var element = $(this);
var target = element.data('agent');
$('body').addClass('agentLoaded');
$('[data-agent-target]').not('[data-agent-target="'+target+'"]').removeClass('active');
$('[data-agent-target="'+target+'"]').addClass('active');
window.location.hash = 'agent='+target;
return false;
});
if(document.location.hash){
var hash = document.location.hash.split('#')[1];
hash = hash.replace('agent=', '');
if(hash && $('[data-agent-target="'+hash+'"]').length) {
$('[data-agent="'+hash+'"]').trigger('click');
}
}
$('.close').click(function() {
$('[data-agent-target]').removeClass('active');
$('body').removeClass('agentLoaded');
return false;
});

[edit] Please see the question in the code
$('[data-agent]').click(function() {
var element = $(this);
var target = element.data('agent');
$('body').addClass('agentLoaded');
$('[data-agent-target]').not('[data-agent-target="'+target+'"]').removeClass('active');
$('[data-agent-target="'+target+'"]').addClass('active');
window.location.hash = 'agent='+target;
return false;
});
if(document.location.hash){ /* What is this for ? */
var hash = document.location.hash.split('#')[1];
hash = hash.replace('agent=', '');
if(hash && $('[data-agent-target="'+hash+'"]').length) {
$('[data-agent="'+hash+'"]').trigger('click');
}
}
$('.close').click(function() {
$('[data-agent-target]').removeClass('active');
$('body').removeClass('agentLoaded');
return false;
});

Related

Set selected navigation option using window.location

I have a theme that sets the selected left navigation option based on what URL you are visiting. However, it breaks if the is a variable attached to the URL, for example www.test.com/abc.aspx?delete=1. The URL www.test.com/abc.aspx works fine and sets the link ABC to active.
I have tried to modify the code to cut off everything after and including ?, but it won't work as intended (nothing in the NAV is selected).
ORIGINAL CODE:
$(function () {
var url = window.location;
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url;
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
MY EDITED CODE:
$(function () {
var url = window.location.toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
I think it is the line with "return this.href == url_fix[0];" that is the culprit.
SOLUTION (what I came up with after reading the comments, thanks guys):
$(function () {
var url = location.href.split("/").slice(-1).toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return $(this).attr("href") == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
Try comparing pathnames instead.
var element = $('ul#sidebarnav a').filter(function () {
return this.pathname == location.pathname;
}).addClass('active').parent().addClass('active');
For example on this page location.pathname returns:
"/questions/48234042/set-selected-navigation-option-using-window-locaiton/48234196"
and does not include location.hash or location.search
I used the answer by #vbguyny to solve the issue. Had to add location.href.split("/").slice(-1).toString(); to get the actual page name, but after that it worked fine. Thanks!

Javascript click event callback not working

I am using javascript to handle click event.
The code is below :
function addClickEventListenerToAllAnchorTag() {
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
var guid = anchor.attributes.getNamedItem('GUID');
if(guid)
{
anchor.addEventListener("click", onClickLoginPopup);
}
}
}
Here I am fetching all anchor tags that has GUID attribute and adding click event listener to it.
But my callback function onClickLoginPopup never gets called.
function onClickLoginPopup(e) {
console.log('onClickLoginPopup');
e.preventDefault();
var host = window.location.hostname;
var url = this.href;
var guid = this.attributes.getNamedItem("GUID");
var mainPopup = document.getElementById('popupMain');
var popupPayment = document.getElementById('popupPayment');
if( mainPopup == null ) {
console.log(mainPopup);
}
else if(userID)
{
showSocialLoginPopup();
return false;
}
if(popupPayment !== null){
showPaymentPopup();
}
//articleLinkClickAction(guid);
return false;
}
Calling Code:
function mpwInit() {
addPopupContents();
addClickEventListenerToAllAnchorTag();
}
includeScripts();
window.onload = mpwInit;
When are you calling addClickEventListenerToAllAnchorTag function ? Have you logged the list of selected anchor elements ? Is it an empty array ? If it is an empty array then you JavaScript code is getting executed before the page loads.

JS popup does't works comparison operator

I have 5 link and mini preview photo and url 3 links its good link opsss and upsss is wrong when i click good link i'm going to new page when i click error link attr href change to adresError and then we have popup This only works for the first time second time click all links have a popup and should have only opsss and upsss
http://jsfiddle.net/3ptktp47/1/
Here is my code :
var nameError = [
"opsss",
"upsss",
];
$(function() {
$('#prev').hide();
$(function() {
var title_link = 'kliknij aby podejżeć';
$(".preview-link a")
.attr({title: title_link})
//.tooltip()
.click(function(){
$('.preview-link a img').css('opacity',1);
var sciezka = $(this).attr("href");
var tytul = $(this).attr("title");
var adres = $(this).text();
//alert(adres);
$(".duzy").attr({ src: sciezka, alt: tytul, style:'cursor:pointer;', href:'http://www.'+ adres,'target':'_blank'});
$('.link').html(adres).attr({href:'http://www.'+ adres,'target':'_blank'});
$('#prev').show();
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.link, .duzy').click(function(event){
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({href:'http://'+ adresError,'target':'_blank'});
});
};
if(adres == 'opsss.com'){
var adresError = 'x4ql.nazwa.pl/'+ nameError[0];
errorDomain();
}else if(adres == 'upsss.com' ){
var adresError = 'x4ql.nazwa.pl/'+ nameError[1];
errorDomain();
}else{
//$('#popup, .popup-bg').fadeOut();
};
$('.cancel, .popup-bg').click(function(event){
$('#popup, .popup-bg').fadeOut();
});
return false;
});
$('.close').click(function(){
$('#prev').hide();
});
$('.link').mouseover(function(){
$(this).css({style: 'color:#000;'});
});
});
});
EDITED:
Ok, I was able to handle your problem.
Your .click() event in the errorDomain() method was firing every time you clicked this square. I managed it to toggle a class on a.duzy element with toggleClass('error') in your if-statement where you check the address.
Inside your click() event, a if-statement is checking if the .duzy element has class named error with hasClass('error') , this has following result -
TRUE- your popup will be displayed
FALSE - nothing happens
I hope my answer is clear enough, but please check out the edited fiddle.
EDITED SOURCE:
Your errorDomain() Method
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.duzy, .link').click(function (event) {
if ($(this).hasClass("error")) {
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({
href: 'http://' + adresError,
'target': '_blank'
});
}
});
}
The if-statements
if (adres == 'opsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[0];
$('a.duzy').toggleClass("error");
errorDomain();
} else if (adres == 'upsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[1];
$('a.duzy').toggleClass("error");
errorDomain();
} else {
$('a.duzy').removeClass("error");
}
Edited fiddle

Getting the next image and previous image from an gallery

I am trying to code my own image gallery using html css jquery. I have a modal window to show the clicked in images. Inside my modal window I have a previous and next button.
My question is how can i show the previous images or next images when someone click that button.
Here's my jsFiddle
jquery code i am using to show clicked in images.
$(function(){
$('.gallery a').click(function(evt) {
evt.preventDefault( );
var imgPath = $(this).attr('href');
$('.gallery-overlay').show()
.find('.gallery-image').attr('src',imgPath);
return false;
});
});
Add this to your jQuery.
Declare a variable current image in your function and keep current image saved in that variable. Update the variable whenever current image is changed.
Updated jsfiddle
Click on the second image in the images and see the prev and next image then.
$('.gallery-control-previous').click(function(){
var imgPath = current_img.prev().attr('href');
current_img = current_img.prev();
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
$('.gallery-control-next').click(function(){
var imgPath = current_img.next().attr('href');
current_img = current_img.next();
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
If you have understood this answer, add checks to the code showing next, prev elemments only when they exist.
You can find how to do that,
here..
Updated.
Get the first child of next row, and pass that.
$('.gallery-control-next').click(function(){
if(current_img.next().length){
current_img = current_img.next();
}else{
current_img = current_img.parents(".row").next(".row").find("a:first");
}
var imgPath = current_img.attr('href');
$('.gallery-overlay').show().find('.gallery-image').attr('src',imgPath);
});
I have added img_no to each a tag to identify the current active image and get next or previous image
Working Demo
$(function () {
$('.gallery a').click(function (evt) {
evt.preventDefault();
var imgPath = $(this).attr('href');
var img_no = $(this).attr('img_no');
$('.gallery-overlay').show()
.find('.gallery-image').attr('src', imgPath).attr('img_no', img_no);
return false;
});
});
i = 1;
$('.row a img').each(function () {
$(this).attr('img_no', i);
$(this).parents('a').attr('img_no', i);
i++;
});
images_length = i - 1;
console.log(images_length);
$('.gallery-control-next').click(function () {
var img_no = $(this).parent().parent().find('.gallery-image').attr('img_no');
img_no++;
if (img_no > images_length) {
img_no = 1;
}
$('.row a').each(function () {
if ($(this).attr('img_no') == img_no) {
imgPath = $(this).attr('href');
}
});
$('.gallery-imagebox img').attr('src', imgPath).attr('img_no', img_no);
});
$('.gallery-control-previous').click(function(){
var img_no = $(this).parent().parent().find('.gallery-image').attr('img_no');
img_no--;
if (img_no <= 0) {
img_no = images_length;
}
$('.row a').each(function () {
if ($(this).attr('img_no') == img_no) {
imgPath = $(this).attr('href');
}
});
$('.gallery-imagebox img').attr('src', imgPath).attr('img_no', img_no);
});

Go To Anchor on Load ( if else statement)

Hi I have a page that navigates using anchors. On load the index page (A) needs to jump to anchor. Fine I can do this with on load function but coming back to the page A from page B I want to jump to a different anchor. I have this working:
<!-- go to Anchor -->
<script type="text/javascript">
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#top") > -1){
window.location.hash="top";
} else {
window.location.hash="middle";
}
}
</script>
#middle is the anchor to use when coming from a link that contains no anchor (or from typing the address into the url bar). I want to add three more 'if's'. I am fairly new at js so bear with me if I am doing something silly. I tried this:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#right") > -1){
window.location.hash="right";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#bottom") > -1){
window.location.hash="bottom";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#left") > -1){
window.location.hash="left";
} else {
window.location.hash="middle";
}
But not joy, the js breaks and no longer goes to #middle on page load.
I tried a wild card approach:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#.") > -1){
window.location.hash=".";
} else {
window.location.hash="middle";
}
}
Again, no joy.
Any help please.. thanks kindly
I am not quite sure I understand the effect you are trying to achieve (since window.location.hash should already contain the hash part of your url), but your code should probably rather be
function goToAnchor() {
var urllocation = location.href;
if (urllocation.indexOf("#right") > -1) {
window.location.hash = "right";
} else if (urllocation.indexOf("#bottom") > -1) {
window.location.hash = "bottom";
} else if(urllocation.indexOf("#left") > -1) {
window.location.hash = "left";
} else {
window.location.hash = "middle";
}
}
I am also guessing that your 'wild card' approach is meant to use regular expressions:
function goToAnchor() {
var urllocation = location.href;
var hashMatch = urllocation.match(/#(.*)/)
if (hashMatch){
window.location.hash = hashMatch[1];
} else {
window.location.hash = "middle";
}
}
Again, I don't quite see what effect this code should have, since window.location.hash will probably have the same value before and after the assignment.
If you just want to go back to the hash in the URL, have you tried something like this?
var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value
window.location.hash = hash; //Set to the old hash

Categories

Resources