How to call different functions when scrolled using JavaScript? - javascript

I was trying to call different functions using JavaScript when a key is pressed. It worked perfectly! How can I achieve the same effect by using the scroll wheel?
The goal is to change the background image of the webpage, carry out a query in a SQL Table and store the x and y co ordinates of the pointer in a table.

Hope this can help :)
$(document).scroll(()=>{
if($(document).scrollTop() >= 970){
//If you want to get style permenent remove line below
$("body").css("background","red");
}
else if($(document).scrollTop() >= 508){
//If you want to get style permenent remove line below
$("body").css("background","blue");
}
else if($(document).scrollTop() >= 8){
//If you want to get style permenent remove line below
$("body").css("background","indigo");
}
})
/*This is for smooth scrolling*/
html {
scroll-behavior: smooth;
}
.big {
height: 500px;
width: 100%;
border: solid black 1px;
}
.active {
color:red;
}
<div id="main">
<div class="big" id ="home">Home</div>
<div class="big" id ="about">About Us</div>
<div class="big" id ="contacts">Contacts</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

You're looking at the onscroll and scroll event.
<div onscroll="myFunction()"></div>
or
document.getElementById("myDIV").addEventListener("scroll", myFunction);
or
document.getElementById("myDIV").onscroll = function() {myFunction()};
and add the function in all cases:
function myFunction() {
console.log("It works");
}
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll
https://www.w3schools.com/jsref/event_onscroll.asp

Related

Why is my if else statement not working? jquery

I have an if else statement that is supposed to hide/show list items when other list items are appended/removed. It only works if I put the if else statement after the #delete-square function but it only works for one list item. Here is my fiddle: http://jsfiddle.net/matty91/zqmps11b/6/
This is probably really simple to do but I don't know javascript/jquery that well.
Example: So for every blue square that is added, take away a green square. There should always be 4 squares present. (if I have 2 blue I should have 2 green. If I have 4 blue then I should have no green. The user should be able to add as many blue squares as he wants but if the blue squares go below 3 then add 1 green) Hopefully that makes sense :)
Let me know if I need to explain a bit more for what I'm trying to accomplish!
Thanks in advance!
$(document).ready(function(){
if ($("ul.db-view-list li .quad #chart_div").length == 1){
$("li.ph:last-child").hide();
} else if($("ul.db-view-list li .quad #chart_div").length == 2){
$("li.ph:nth-child(2)").hide();
} else if($("ul.db-view-list li .quad #chart_div").length == 3){
$("li.ph:nth-child(1)").hide();
} else if($("ul.db-view-list li .quad #chart_div").length >= 4){
$("li.ph:first-child").hide();
} else {
$("li.ph").show();
};
$(".add-square").click(function(){
$(".db-view-list").prepend("<li><button id='delete-square'>X</button><div class='quad'><div id='chart_div'></div></div></li>");
$(document).on('click', '#delete-square', function(){
$(this).parent().remove();
});
});
});
.db-view-list{
padding: 0px;
margin: 0px;
height: 300px;
}
.db-view-list li{
padding:0px;
list-style-type: none;
}
.quad{
width: 100px;
height: 100px;
float: left;
}
.default-message{
background-color: green;
border: solid 1px white;
width: 100%;
height: 100%;
margin:0px;
padding: 0px;
}
#chart_div{
width: 100%;
height: 100%;
background-color: blue;
border: solid 1px white;
}
#delete-square{
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="db-view-list">
<li class="ph">
<div class="quad">
<p class="default-message">
click add square to add a graph first
</p>
</div>
</li>
<li class="ph">
<div class="quad">
<p class="default-message">
click add square to add a graph 2
</p>
</div>
</li>
<li class="ph">
<div class="quad">
<p class="default-message">
click add square to add a graph 3
</p>
</div>
</li>
<li class="ph">
<div class="quad">
<p class="default-message">
click add square to add a graph last
</p>
</div>
</li>
</ul>
<button class="add-square">
add square
</button>
http://jsfiddle.net/zqmps11b/28/
Keep in mind the CSS is changed as well to accommodate Classes instead of IDs.
Your if statements were setup to only be checked on document.ready which only occurs once. This should work:
var numOfNewBoxes = 0;
// declare variable to count new boxes.
$(document).ready(function () {
// the if/else statement should be removed from the document.ready function
//You're not reloading the page every time you tap the 'add square button
//change the ids to classes because there should only be 1 instance of each ID.
$(".add-square").click(function () {
$(".db-view-list").prepend("<li><button class='delete-square'>X</button><div class='quad'><div class='chart_div'></div></div></li>");
//hide the last of the original boxes that are visible
$('.default-message:visible:last').hide();
numOfNewBoxes ++;
//remove any old on click events attached to the class delete-square
$('.delete-square').off('click');
//assign the event to the delete square class only - not the document.
//This stops the event from continuously firing on click.
$('.delete-square').on('click', function () {
numOfNewBoxes --;
//show the first of the original boxes if they are hidden
// only if there are < 4 new boxes;
$(this).parent().remove();
(numOfNewBoxes < 4) ? ($('.default-message:hidden:first').show()) : false;
});
});
});
Since you need to have more than one chart_div and delete_button, you can't use that as an id. Use a class instead:
$(document).ready(function () {
var chartDivs = $("ul.db-view-list li .quad .chart_div");
if (chartDivs.length == 1) {
$("li.ph:last-child").hide();
} else if (chartDivs.length == 2) {
$("li.ph:nth-child(2)").hide();
} else if (chartDivs.length == 3) {
$("li.ph:nth-child(1)").hide();
} else if (chartDivs.length >= 4) {
$("li.ph:first-child").hide();
} else {
$("li.ph").show();
}
;
$(".add-square").click(function () {
$(".db-view-list").prepend("<li><button class='delete-square'>X</button><div class='quad'><div class='chart_div'></div></div></li>");
});
//this will apply to .delete-squares created in the future
//so you can just do it once.
$(document).on('click', '.delete-square', function () {
$(this).parent().remove();
});
});
I believe you should also put that if/else statement in a function and have it execute whenever you delete or add a div. Now, the if/else statement is only executed once: when the document is ready.

How to show div with slide down effect only with javascript

I Want to show div on click with slideup effect using javascript(not jquery).
Here is my HTML code:-
<div class="title-box">show text</div>
<div class="box"><span class="activity-title">our regions bla bla</span></div>
Kindly advise me asap.
The question states that the solution needs to be done with pure JavaScript as opposed to jQuery, but it does not preclude the use of CSS. I would argue that CSS is the best approach because the slide effect is presentational.
See http://jsfiddle.net/L9s13nhf/
<html><head>
<style type="text/css">
#d {
height: 100px;
width: 100px;
border: 1px solid red;
margin-top: -200px;
transition: margin-top 2s;
}
#d.shown {
margin-top: 100px;
}
</style>
</head>
<body>
<button id="b">Toggle slide</button>
<div id="d">Weeeeeeee</div>
<script type="text/javascript">
var b = document.getElementById('b');
var d = document.getElementById('d');
b.addEventListener('click', function() {
d.classList.toggle('shown');
});
</script>
</body></html>
The basic algorithm is to add a class to the element you want to slide in/out whenever some button or link is clicked (I'd also argue that a button is more semantically appropriate here than an anchor tag which is more for linking web pages).
The CSS kicks in automatically and updates the margin-top of the sliding element to be visible on-screen. The transition property of the element tells the browser to animate the margin-top property for two seconds.
You can try below code:
Working Demo
document.getElementById('bar').onclick = (function()
{
var that, interval, step = 20,
id = document.getElementById('foo'),
handler = function()
{
that = that || this;
that.onclick = null;
id = document.getElementById('foo');
interval =setInterval (function()
{
id.style.top = (parseInt(id.style.top, 10) + step)+ 'px';
if (id.style.top === '0px' || id.style.top === '400px')
{
that.onclick = handler;
clearInterval(interval);
if (id.style.top === '400px')
{
id.style.display = 'none';
}
step *= -1;
}
else
{
id.style.display = 'block';
}
},100);
};
return handler;
}());
You can refer following below:
<div class="title-box">
show text
</div>
<div class="box" id="slidedown_demo" style="width:100px; height:80px; background:#ccc; text-align:center;">
<span class="activity-title">our regions bla bla</span>
</div>

How to toggle two images onClick

I'm making a collapsible treeView.
I made it all, I just need my + and - icons to toggle whenever they are clicked.
I did the part when I change an icon from + to -, on click, with jQuery with the following code:
$(this).attr('src','../images/expand.gif');
Problem is, I don't know how to make it go other way around, when i click on the node again :)
This should work:
<style>
.expand{
content:url("http://site.com/expand.gif");
}
.collapse{
content:url("http://site.com/collapse.gif");
}
</style>
<img class="expand">
<script>
//onclick code
$('img.expand').toggleClass('collapse');
</script>
Look for jquery function toggleClass :)
http://jsfiddle.net/Ceptu/
Html:
<div id="box">
Hello :D
</div>
Jquery:
$("#box").click(function () {
$(this).toggleClass("red");
});
Css:
#box {
width: 200px;
height: 200px;
background-color: blue;
}
.red {
background-color: red !important;
}
Remember that !important is realy important!!!
Lots of ways to do this :D
I wanted to do this without making classes. Inside your click event function, you could do something like this:
if($(this).attr('src') == '../images/collapse.gif')
$(this).attr('src', '../images/expand.gif');
else
$(this).attr('src', '../images/collapse.gif');
add plus as a default img src then define a minus-class to change the image source to minus image
$("selector_for_your_link").click(function () {
$(this).toggleClass("minus-class");
});

How to hide/show div tags using JavaScript?

Basically, I'm trying to make a link that, when pressed, will hide the current body div tag and show another one in its place, unfortunately, when I click the link, the first body div tag still appears. Here is the HTML code:
<div id="body">
<h1>Numbers</h1>
</div>
<div id="body1">
Body 1
</div>
Here is the CSS code:
#body {
height: 500px;
width: 100%;
margin: auto auto;
border: solid medium thick;
}
#body1 {
height: 500px;
width: 100%;
margin: auto auto;
border: solid medium thick;
display: hidden;
}
Here is the JavaScript code:
function changeDiv() {
document.getElementById('body').style.display = "hidden"; // hide body div tag
document.getElementById('body1').style.display = "block"; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; // display text if JavaScript worked
}
NB: CSS tags are declared in different files
Have you tried
document.getElementById('body').style.display = "none";
instead of
document.getElementById('body').style.display = "hidden";?
just use a jquery event listner , click event.
let the class of the link is lb... i am considering body as a div as you said...
$('.lb').click(function() {
$('#body1').show();
$('#body').hide();
});
Use the following code:
function hide {
document.getElementById('div').style.display = "none";
}
function show {
document.getElementById('div').style.display = "block";
}
You can Hide/Show Div using Js function. sample below
<script>
function showDivAttid(){
if(Your Condition)
{
document.getElementById("attid").style.display = 'inline';
}
else
{
document.getElementById("attid").style.display = 'none';
}
}
</script>
HTML -
Show/Hide this text
Set your HTML as
<div id="body" hidden="">
<h1>Numbers</h1>
</div>
<div id="body1" hidden="hidden">
Body 1
</div>
And now set the javascript as
function changeDiv()
{
document.getElementById('body').hidden = "hidden"; // hide body div tag
document.getElementById('body1').hidden = ""; // show body1 div tag
document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked";
// display text if JavaScript worked
}
Check, it works.
Consider using jQuery. Life is much easier with:
$('body').hide(); $('body1').show();
try yo write
document.getElementById('id').style.visibility="hidden";

Best practice for a button with image and text in mobile website

Refer to the screenshot below, I have created a div to wrap another two div of image and text, then I use CSS position: absolute to make these div merge together.
However, I found that the button is not sensitive while testing on mobile devices, sometime I need to touch the button few time to take effect.
So, is there something wrong for my code and what is the best practice to create a button with image and text?
Thanks
<div class="r">
<div class="a">
<div class="i"><img src="store_btn_on.png" /></div>
<div class="t">Shatin</div>
</div>
<div class="b">
<div class="i"><img src="store_btn_off.png" /></div>
<div class="t">Causeway Bay</div>
</div>
<div class="c">
<div class="i"><img src="store_btn_off.png" /></div>
<div class="t">Kowloon Bay</div>
</div>
</div>
Update for the part of javascript
addButtonListener($("#store > .r > .a"), function(event, target){
$("#some_content").css("display", "none");
$("#other_content").css("display", "block");
$(".r > .b > .a > img").attr("src" , "store_btn_on.png");
$(".r > .b > .b > img, .r > .b > .c > img").attr("src" , "store_btn_off.png");
});
function addButtonListener(targets, job){
if ("ontouchstart" in document.documentElement){
targets.each(function(){
$(this)[0].addEventListener('touchstart', function(event){
event.preventDefault();
$(this).attr({ "x": event.targetTouches[0].clientX, "diffX": 0, "y": event.targetTouches[0].clientY, "diffY": 0 });
$(this).addClass("on");
}, false);
$(this)[0].addEventListener('touchmove', function(event){
$(this).attr({
"diffX": Math.abs(event.targetTouches[0].clientX - $(this).attr("x")),
"diffY": Math.abs(event.targetTouches[0].clientY - $(this).attr("y"))
});
}, false);
$(this)[0].addEventListener("touchend", function(event){
$(this).removeClass("on");
if ($(this).attr("diffX") < 5 && $(this).attr("diffY") < 5){ $(job(event, $(this))); }
}, false);
});
}
else {
targets.each(function(){
$(this).mousedown(function(event){ event.preventDefault(); $(this).addClass("on"); });
$(this).mouseup(function(event){ event.preventDefault(); if ($(this).hasClass("on")){ $(job(event, $(this))); } $(this).removeClass("on"); });
$(this).hover(function(event){ $(this).removeClass("on"); });
});
}
}
I am not sure about the sensitivity of your button on mobile devices (you haven't shown any of your code for handling click events), but I think it is better to write your HTML like this:
<div class="r">
<div class="button on">
<span>Shatin</span>
</div>
<div class="button">
<span>Bay</span>
</div>
<div class="button">
<span>Bay</span>
</div>
</div>
Then use CSS in your stylesheet:
.button {
background: url(http://domain.com/images/store_btn_off.png) no-repeat 0 0;
/* Additional button styles */
}
.button.on {
background: url(http://domain.com/images/store_btn_on.png) no-repeat 0 0;
}
.button span {
color: #FFF;
margin: auto;
}
This makes it easy to dynamically turn a button on or off just by adding or removing the on class.
Although not necessary, you may also be interested in looking at CSS3 gradients to create simple gradient background images like that, and then degrade nicely to an image in browsers without any gradient support.
The class names "r" and "b" are not very descriptive. Unless some HTML/CSS minifier put those there and you have proper names in your development code, I would consider giving your classes more descriptive names as well.

Categories

Resources