Ok so I'm trying to make a sub navigation menu that changes the active state of menu items when the user scrolls to the element the anchor link is on. I have managed to get that part of the code working well however I don't want this to occur when someone clicks a link and it auto scrolls them to that section.
So all this code is happening when the user scrolls, if I could disable it when the user clicked an anchor link that would be ideal.
$(window).scroll(function(){
$(".sticky_button").each(function(){
var ele_id = $(this).find('a').attr('href');
check_collision($(this),$(ele_id));
});
});
function check_collision(fixed_element,relative_element){
var sticky = $(".sticky_component");
var fixed_position = sticky.offset().top;
var fixed_height = sticky.height() + 10;
var toCross_position = relative_element.offset().top;
var toCross_height = relative_element.outerHeight();
if(fixed_position + fixed_height > toCross_position && fixed_position + fixed_height < toCross_position + toCross_height){
if(!fixed_element.hasClass("active")){
fixed_element.siblings().removeClass("active");
fixed_element.addClass("active");
return false;
}
}
}
Related
I'm having pagination issue to the next page. I want to navigate to next page and stop at the page. Eg: navigate to page 2 and stop at page 2. The code works well in Firefox. However, when i run the code in chromium. the pagination navigate to next page twice and stop at page 3.
var a = document.querySelector('pre').innerText;
var data = JSON.parse(a);
var item = data.products;
var result = [];
var TotalItems = item.length;
if(TotalItems === 200){
var nextPageNum = parseInt(document.URL.toString().match(/page=(\d*)/)[1]) + 1;
var nextPage = "page=" + nextPageNum;
var nextPageURL = "https://abc.com.au/products.json?" + nextPage + "&limit=200";
window.open(nextPageURL,"_self")
}
else{
window.open("https://abc.com.au","_self")
}
it works fine if the nextPageURL in the if statement is replace by a string.
i tried to change the document.URL to:
window.location.href / document.location.href / document.baseURI
but the result is still the same
I start with a button that activates the function onclick:
<button onclick="openStuff();">Click here!</button>
Then, I have an array of links like so:
var links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"];
Finally, I define the function that randomly applies a link to the button from the above array:
openStuff = function () {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'https://' + links[randIdx];
// open it in a new window / tab (depends on browser setting)
window.open(link);
};
The problem is I need it to not be random. Rather, I need it to go down the list sequentially as the user clicks the button. If the user clicks the button once it should go to the first link. But, if this user clicks the button a second time it should go to the second link in the list.
For example: User clicks button: Go to first link, User clicks button again: go to second link, and so on.
var linkIndex = 0;
openStuff = function () {
//when no more links are available to click then return
if(links.length <= linkIndex) return;
// construct the link to be opened
var link = 'https://' + links[linkIndex];
// open it in a new window / tab (depends on browser setting)
window.open(link);
linkIndex++;
};
You need a global index that start in 0. Then, inside the function you increment it after open the link.
var link = 'https://' + links[index];
index++;
I would do it like this:
var special_button_state = 0;
const links = [
"msn.com",
"google.com",
"youtube.com",
"bbc.com",
"facebook.com",
"cnn.com",
"fox.com",
"techcrunch.com"
];
const openStuff = function () {
var link = 'https://' + links[special_button_state];
if(special_button_state < links.length-1) {
special_button_state++;
}
window.open(link);
console.log(link);
};
<button onclick="openStuff();">Click here!</button>
You could have another variable set to the first index of the array, something like:
var linkTarget = 0
and then update linkTarget in the function to increment appropriately:
openStuff = function () {
// construct the link to be opened
var link = 'https://' + links[linkTarget];
// open it in a new window / tab (depends on browser setting)
window.open(link);
// update the index
if (linkTarget++ == links.length)
linkTarget = 0
};
You could also implement a dynamic label so that you know where it's going:
<body onload="setLink()">
<button id="turntable-button" onclick="openStuff()" />
</body>
Label setter on page load (put the same getElementById() line in openStuff() after updating the index):
setLink = function() {
document.getElementById("turntable-button").innerHTML = links[linkTarget];
}
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;
}
I am trying to use this right-click context menu. It works visually as hoped, however I dont know where to begin to apply actual actions when menu items are clicked. Obviously right now all it says is Back menu item was clicked - target id...., Obiviously when someone clicked back it would actually take them back a page vice just stating what they clicked.
here is the jquery that generates the menu
<script>
var callback = function(target,element){
$(target).html('<span style="color:red">' +$(element).html() +'</span> menu is clicked, Target id: '+ $(target).attr('id'));
};
var menu = {};
menu['back'] = {icon:'icon-arrow-left',text:'Back',click:callback};
menu['forward'] = {icon:'icon-arrow-right',text:'Forward',click:callback};
menu['view'] = {text:'View',click:callback};
menu['sortby'] = {text:'Sort by',click:callback};
menu['refresh'] = {icon:'icon-refresh',text:'Refresh',click:callback};
menu['notepad'] = {text:'Notepad++',click:callback};
menu['s1'] = '---';
menu['copy'] = {text:'Copy',click:callback};
menu['paste'] = {disabled:true,text:'Paste',click:callback};
menu['paste_shortcut'] = {disabled:true,text:'Paste shortcut',click:callback};
menu['s2'] = '---';
menu['create_shortcut'] = {text:'Create shortcut',click:callback};
menu['rename'] = {text:'Rename',click:callback};
menu['del'] = {text:'Delete',click:callback};
menu['s3'] = '---';
menu['properties'] = {text:'Properties',click:callback};
$('#id0').contextMenu(menu);
$('body').contextMenu(menu);
$('body').contextMenu('beforeDisplay',function(target){ console.log(target.html()) });
</script>
Thanks for any help/guidance where to look or how to get started in advance!
Replace
function(target){ console.log(target.html()) }
with a function that performs your actions.
I'm trying to prevent default links, because I'm dynamically loading pages into divs with jQuery, and the href for each like is just the name before the page (e.g. href=home, and fixing to load to home.php in code below).
//initialize home page as active on load up and deactivate link
var activePage = $('a[href$="home"]');
var activePageHref = activePage.attr('href');
activePage.attr('href', '#');
$('a').click(function(e) {
e.preventDefault();
//set the page clicked on
var page = $(this).attr('href');
//check to see if there are any extras to url for php
var pageCheck = page.split('?');
//sort page type
if (pageType == null) {
//dynamically load the page in div bodycontent
$('#bodycontent').load(page + '.php');
} else {
$('#bodycontent').load(page + '.php?' + pageCheck[1]);
}
//pull up last disabled link for navigation
var setOld = $('a[href$="' + activePageHref + '"]');
setOld.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page;
//make link inactive
$(this).attr('href', '#');
});
It was ok with return false at the end until I added MORE things I needed to happen in the click event function, but to be exact, this part:
//pull up last disabled link for navigation
var setOld = $('a[href$="' + activePageHref + '"]');
setOld.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page;
//make link inactive
$(this).attr('href', '#');
Now the e.preventDefault();, which is from what I understand the correct way of doing what I need to happen, is stopping the entire thing from firing on any links. I'm stuck. I just need to stop default action, and use the function I've built with the extras at the end I've added to make my navigation pretty.
Also to add, I do have a hover function tied to the ul of this navigation, but didn't include it as it shouldn't causing an issue, but I can put it in here if needed. That is the only other thing in this document ready function.
Updated:
Since you change the disabled link's href initially, the attribute-contains selector won't be able to find it again later on to activate it. I would suggest doing this a little bit differently.
You can capture the entire 'disabled link' functionality by using classes. If you add a class to links which should be "disabled" you can prevent the browser from following only links with that specified class.
When you click on an "enabled link", follow it then make it disabled. Then, enable all other links.
$('a').click(function() {
$(this).addClass('disabledLink');
$('a').not(this).removeClass('disabledLink');
}
Then, set up an event listener for the whole document which prevents the default action on links with a certain class.
$(document).on('click', 'a.disabledLink', function(e) {
e.preventDefault();
}
This should achieve what you want as is (i.e. it would replace your entire 'click' handler above). Note with this the href will never be changed to '#'.
Otherwise: just cache the link itself along with its href
//pull up last disabled link for navigation
activePage.attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = $(this);
activePageHref = $(this).attr('href');
//make link inactive
$(this).attr('href', '#');
You have a syntax error which is causing the JS engine to halt:
//pull up last disabled link for navigation
$('a[href$="' + activePageHref + '"]').attr('href', '' + activePageHref + '');
//set the new disabled link for navigation
activePage = page.attr('href');
/* THIS HERE RETURNS A STRING SO YOU CHANGE activePage to a string. */
// Should probably be:
activePageHref = page.attr('href');
//make link inactive
activePage.attr('href', '#');
Befor you invoke this method you set activePage to be a string, which has no method .attr() so it throws an error and execution of the function stops.