Autoscroll when div appears and when details/summary is clicked - javascript

I'm trying to figure out how to add autoscroll till the end of the page/div in 2 different situations as I'm new to JS.
1)When a div is appearing from display:none to block.
For example, here is when my alert appears and I want it to be fully shown. Is there a way to add in a piece of automatic code here? I made it mechanically so far.
document.querySelector('button').onclick = function() {
if(document.querySelector('select').value === "a") {
rightAlert.style.display = 'block';
wrongAlert.style.display = 'none';
window.scrollBy(0, 100);
}
When details/summary are clicked and expanded, with the traditional structure (Details, Summary, P)
Tried
document.querySelector('summary').onclick = function() {
window.scrollBy(0, 100);
};
but it didn't work.
Thanks a lot!

Related

How to hide an element if the page contains a specific url / word?

With JavaScript I'm trying to hide an element that contains a text message when the page URL is my-website.com/login/?lost_pass=1. I managed to hide the tag but it doesn't work as I expected.
The unwanted tag is actually hidden, but the same also happens when the page is my-website.com/login while it should only be hidden if the page is my-website.com/login/?lost_pass=1
So, for example, you are on my-website.com/login, but when you click "lost password" the page reloads to show a different form, so the URL becomes my-website.com/login/?lost_pass = 1
Can anyone help me with this? I don't understand where I'm wrong.
I tried this, but the tag is hidden on all pages
window.onload = function() {
if (window.location.href.indexOf('?lost_pass=1')) {
//Hide the element.
document.querySelectorAll('#msg_social')[0].style.display = 'none';
}
};
Then I tried that, but the tag is not hidden in any of the pages
if (window.location.href.indexOf("?lost_pass=1") != -1) {
$("#msg_social").hide();
}
Your onload code has a if that always pass :
window.onload = function() {
// this if will always pass, any number will pass that if like -1, 25 etc...
if (window.location.href.indexOf('?lost_pass=1')) {
//Hide the element.
document.querySelectorAll('#msg_social')[0].style.display = 'none';
}
};
it's better to use .contains :
window.onload = function() {
if (!window.location.href.includes('?lost_pass=1')) {
//Hide the element.
document.querySelectorAll('#msg_social')[0].style.display = 'none';
}
};
it's shorter and avoid forgetting about the != -1 thing

loop through wordpress articles and add a css class with js

I hope you have a good day :)
I am working on a plugin currently. I would like to loop through all the articles: on click => open a popp-up, when the pop-up closes => show this content ... My code only works for the first article. Sorry if that seems trivial to you, if you have links or tutorials to advise me, I am interested :)
Thank you !
function socialLocker() {
let sl = document.querySelector(".ws-sl-container");
let slc = document.querySelector(".ws-sl-content");
document.querySelectorAll(".ws-sl-box-for-social-medias a").forEach(function(ele) {
ele.onclick = function(e) {
var web_window = window.open(this.href, 'Share Link', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600,top=' + (screen.height/2 - 300) + ',left=' + (screen.width/2 - 300));
var check_window_close = setInterval(function() {
if (web_window.closed) {
clearInterval(check_window_close);
sl.style.display = "none";
slc.style.display = "block";
}
}, 1000);
e.preventDefault();
};
});
};
It seems to be a problem with selecting the elements in the document.
You can use next selector: https://api.jquery.com/next/ instead of selecting all and looping with foreach. With next, you will get the closest element.
Suppose all the posts in your list have a button with the class trigger and when clicked it shows a popup with the class of popup.
<script>
jQuery(document).ready(function(){
jQuery(".popup").hide(); /* hide all popups */
jQuery(".trigger").click(function(){ /* when button is clicked */
jQuery(this).next(".popup").slideToggle(); /* toggle the closest popup */
});
});
</script>
This way the click / action (you want to have it when closed) on (this) element will affect nearest element.

How to Expand / Collapse a section of a Web Site and also change the image using JavaScript

EDIT #1
Thanks to the 2 users who responded, their solutions worked great! Something I forgot to mention in the original post was, Is there any way to adjust the user's view so that when the expanded section is collapses by the user, their "view" (or the actual web page) can adjust up to an anchored spot?
ORIGINAL POST
I've got a section of a website that I want to first be collapsed and not able to be viewed by the user. Then, when they hit an arrow on the screen, the hidden content will then display AND the image needs to change from a "down" arrow to an "up" arrow.
I'm able to do this with the below code right now but I have to have two arrows. Can anyone help so that I only have one arrow on screen and it changes based on when the user clicks on it? I'd also like this to be able to be done an infinite amount of times by the user (ie if the user clicks the "down" arrow, the section expands and the arrow changes to an "up" arrow but then when the user hits that "up" arrow the section collapses and the arrow changes back to a "down" arrow. Possible?
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl(h) {
var tbl = document.getElementById('tbl');
tbl.style.display = h;
}
// -->
</script>
<br>
<img src="up_arrow.png">
<img src="down_arrow.png">
Thanks for any help!
I have added your code and created a jsfiddle for you...
changed code:-
function sizeTbl(h) {
var tbl = document.getElementById('container');
tbl.style.display = h;
if (h == "block") {
document.getElementById('down').style.display = 'none';
document.getElementById('up').style.display = 'block';
} else {
document.getElementById('up').style.display = 'none';
document.getElementById('down').style.display = 'block';
}
}
working example:-
click to see example:-http://jsfiddle.net/XUjAH/1089/
thanks
I've taken out the parameter from your sizeTbl method
Then I'm getting the src property of the image (note I've given it an ID). Depending on the src we can show/hide the table and change the image property
Here's a jsFiddle
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.src === 'down_arrow.png'){
tbl.style.display = 'block';
icon.src = 'up_arrow.png';
}
else {
tbl.style.display = 'none';
icon.src = 'down_arrow.png';
}
}
// -->
</script>
<br>
<img src="down_arrow.png" id="toggle-table">
You've added some extra requirements to your question. You've tagged jQuery and this is the easiest solution for this scenario.
Remove the javascript:sizeTbl() from your <anchor> tag. This is known as inline JS and isn't recommended because it means you are mixing your presentation code with your business logic.
You make the <anchor> tag act like a normal anchor tag and attach a click event in the document's ready event.
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.innerText === 'show') {
tbl.style.display = 'block';
icon.innerText = 'hide';
} else {
tbl.style.display = 'none';
icon.innerText = 'show';
}
}
$(document).ready(function(){
$('#sizeTbl').on('click', sizeTbl);
});
I've created a new jsFiddle that demonstrates this.
Notes:
You need to be using jQuery for this to work
Note that I've given the <anchor> tag an ID. This is so that I can locate it in code
If you have any other comments, the etiquette on SO is to ask new questions. The answers get too long and complicated otherwise

How to disable scrolling in outer elements?

I have a vertically-scrolling div within a page that also scrolls vertically.
When the child div is scrolled with the mouse wheel and reaches the top or bottom of the scroll bar, the page (body) begins to scroll. While the mouse is over the child div, I'd like the page (body) scroll to be locked.
This SO post (scroll down to the selected answer) demonstrates the problem well.
This SO question is essentially the same as mine, but the selected answer causes my page contents to noticeably shift horizontally as the scrollbar disappears and reappears.
I thought there might be a solution that leverages event.stopPropagation(), but couldn't get anything to work. In ActionScript, this kind of thing would be solved by placing a mousewheel handler on the child div that calls stopPropagation() on the event before it reaches the body element. Since JS and AS are both ECMAScript languages, I thought the concept might translate, but it didn't seem to work.
Is there a solution that keeps my page contents from shifting around? Most likely using stopPropagation rather than a CSS fix? JQuery answers are welcome as is pure JS.
here's what i ended up with. very similar to #mrtsherman's answer here, only pure JS events instead of jQuery. i still used jQuery for selecting and moving the child div around, though.
// earlier, i have code that references my child div, as childDiv
function disableWindowScroll () {
if (window.addEventListener) {
window.addEventListener("DOMMouseScroll", onChildMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = onChildMouseWheel;
}
function enableWindowScroll () {
if (window.removeEventListener) {
window.removeEventListener("DOMMouseScroll", onArticleMouseWheel, false);
}
window.onmousewheel = document.onmousewheel = null;
}
function onChildMouseWheel (event) {
var scrollTgt = 0;
event = window.event || event;
if (event.detail) {
scrollTgt = -40 * event.detail;
} else {
scrollTgt = event.wheelDeltaY;
}
if (scrollTgt) {
preventDefault(event);
$(childDiv).scrollTop($(childDiv).scrollTop() - scrollTgt);
}
}
function preventDefault (event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
}
event.returnValue = false;
}
i've noticed the scrolling doesn't match normal scrolling exactly; it seems to scroll a bit faster than without this code. i assume i can fix by knocking down wheelDeltaY a bit, but it's odd that it would be reported differently by javascript than it's actually implemented by the browser...
I usually do it with a small hack listening to the scroll event on the document: it resets the scroll height back to the original one - effectively freezing the document from scrolling but any inner element with overflow: auto will still scroll nicely:
var scrollTop = $(document).scrollTop();
$(document).on('scroll.scrollLock', function() {
$(document).scrollTop(scrollTop);
});
and then when I'm done with the inner scroll lock:
$(document).off('scroll.scrollLock');
the .scrollLock event namespace makes sure I'm not messing with any other event listeners on scroll.
Although this is an old question, here is how I do it with jQuery. This allows you to scroll a list within an outer list, or you can change the outer list to the document to do what the OP asked.
window.scrollLockHolder = null;
function lockScroll(id){
if (window.scrollLockHolder == null){
window.scrollLockHolder = $('#' + id).scrollTop();
}
$('#' + id).on('scroll', function(){
$('#' + id).scrollTop(window.scrollLockHolder);
});
}
function unlockScroll(id){
$('#' + id).off('scroll');
window.scrollLockHolder = null;
}
And you can use it like this:
<ul onmousemove="lockScroll('outer-scroller-id')" onmouseout="unlockScroll('outer-scroller-id')">
<li>...</li>
<li>...</li>
</ul>
what about this:
div.onmousemove = function() { // may be onmouseover also works fine
document.body.style.overflow = "hidden";
document.documentElement.style.overflow = "hidden";
};
div.onmouseout = function() {
document.body.style.overflow = "auto";
document.documentElement.style.overflow = "auto";
};

Jquery - Carasol build finished and would like advice on best practice / neatening up my code

I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.

Categories