How can I change a modal popup every 30 seconds? - javascript

I have a div id called modalpage
and have css. I need a javascript function which can dynamically shows popup for 20 mins and change in every 30 secs right now i have the following javascript function. Can anybody help me please
<script language="javascript" type="text/javascript">
function revealModal(divID)
{
window.onscroll = function () {
document.getElementById(divID).style.top = document.body.scrollTop;
};
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
which is called by a input id button.
<input id="Button1" type="button" value="Click here" onclick="revealModal('modalPage')" />
Thanks
This is what i came up with
function revealModal(divID)
{
var i = 1;
divID.replace('*', i);
setInterval(function(){revealModal(divID)},1000);
i = i + 1;
if (i == 3) i = 1;
var div = getElementById(divID)
window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
but this is not working its showing the modular_3 every time. is it because of all three divs are in the same file ??
<input id="Button1" type="button" value="Click heres" onclick="revealModal('modalPage_*')" />

Well, for one thing don't put that set interval inside the function. That would start a never ending cycle on the first click that would keep triggering the div id it was passed.
What you should probably do is keep an array of id's that should be updated and loop through that in the function...
var divs = [];
function addID(id)
{
divs.push(id);
}
function revealModal()
{
for(var i = 0; i < divs.length; i ++)
{
var div = getElementById('modalPage_' + divs[i]);
window.onscroll = function () {
div.style.top = document.body.scrollTop;
}
div.style.display = "block";
div.style.top = document.body.scrollTop;
}
}
setInterval(function(){revealModal()},1000);
And your html buttons:
<input id="Button1" type="button" value="Click heres" onclick="addID('1')" />
<input id="Button2" type="button" value="Click heres" onclick="addID('2')" />
<input id="Button3" type="button" value="Click heres" onclick="addID('3')" />
Now consider this - I don't really understand your request. It looks like a bunch of others don't understand either. The way I saw it was you want to reveal a div on click and make sure it updates every nth seconds. In this case, it looks like you chose 1000 ms, or every 1 second even though you said you wanted every 30 seconds. Fair enough, change that 1000 to 30000.
It looks like the ONLY update you do is make sure it sticks to a certain position on the screen and NOT updates the content.
So what I've done is make the interval outside the function so it is always going. Then on click you push the id into the divs array where the interval will update only what is inside the loop. While conceptually this will work, it seems like a bad way to do it.
You should just use an easy library like jquery and place a scroll listener that updates the position whether or not they're revealed. Seeing as you specified jquery in your tags but don't use a lick of it in your example, I assume that means you're not entirely familiar with the library.
This could be done by simply adding a class of "modal" to every modal div and using this:
$(document).ready(function(){
$(window).scroll(function(){
$('.modal').css('top', $(window).scrollTop() + 'px');
});
$('.modal').on('click', function(){
$(this).css('display', 'block');
});
});
Of course you would need to call the jquery library before this call for this to work.

Related

How do I make a button disappear after a certain amount of clicks

I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on!
any response is appreciated!
Use this Code
HTML:
<button type='button' id='button_test_clicks'>
Click me!
</button>
JavaScript:
(function(){
var counter=0; // counter clicks initialization
var button=document.getElementById('button_test_clicks'); //Our button
button.addEventListener("click",function(){ //add a click event to button
counter++; //incement the counter
console.log(a);
if(counter==5){
button.style.display = 'none'; //hide if the clicks reached to 5
}
});
})();
But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage in javascript.
Assign id to your button.
<Button id='myButton' onclick="myFunction()">
On every click of button, keep incrementing the counter (I think you know how to do it)
After the counter is reached,
document.getElementById("Your_button_id_here").style.visibility = "hidden";
<script>
var counter=0;
function myFunction() {
//increment counter
counter+=1;
if(counter>4)
document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>
However, I think disabling would be more proper:
document.getElementById("Your_button_id_here").disabled=true
You could have a simple script like this :
var nbClicks=0;
function btnOnClick(btn){
if(++nbClicks>5){btn.style.display='none';}
}
And use it like that :
<input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">
On every click just increment a variable's value and after got desired number, hide it by css and js.
I made a small example with jQuery
var count = 0;
$("#b1").click(function() {
count++;
if (count >= 5) {
$("#b1").hide();
}
});
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<button id="b1">5 Clicks</button>
</body>
</html>

How to toggle <p> once you click on <button> for second time?

function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<button type= "button" onclick="testFunction()"> Click Here! </button>
I am wondering how I hide the paragraph once a user clicks on the button a second time? When user clicks on button the first time, javascript is enabled and the code is shown, but then paragraph stays on the screen even after user clicks for a second time on button. Is there some way I can hide what is displayed if user clicks on button for a second time?
<p id= "test"> **I would like to hide this once user clicks on button for a second time!!** </p>
<script>
function testFunction(){
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
</script>
<button type= "button" onclick="testFunction()"> Click Here! </button>
First of all, I don't think that you should alter the style of elements trough js, that is what css is for (exceptions exist obviously). You could however alter the state of an element, and have your css react to that. I find it keeps your code a lot easier to maintain, and you know automatically where to look for what when you need to change something.
Have a look at the fiddle I prepared: http://jsfiddle.net/7xy39ufz/1/
So I added a state to your markup (I went for a data attribute, but a class or something could do as well)
<p id="test" data-visible="0">...</p>
<button type="button" id="button">...</button>
Then in the css I added a few lines that would react to the state:
p {
font-size: 50px;
color: blue;
}
p[data-visible="0"] {
display: none;
}
p[data-visible="1"] {
display: block;
}
And with all that done the javascript becomes very simple
document
.getElementById('button')
.addEventListener('click', testFunction, false);
function testFunction(){
var x = document.getElementById("test");
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
}
Note that I moved the binding of the click event to js as well, in part because I couldn't get it to work in the fiddle (a scope / sandbox issue i guess), but mainly because I find js belongs with js, not in your markup.
Update
The real 'magic' is indeed being done in this line:
x.dataset.visible = x.dataset.visible == 0 ? 1 : 0;
This is basically a short hand for
if (x.dataset.visible == 0) {
x.dataset.visible = 1;
} else {
x.dataset.visible = 0;
}
(look up 'ternary' if you want to learn more about the syntax)
This code switches the data-visible attribute of you p between 1 and 0. The css reacts to that by setting the display property of that paragraph (that is what the attribute selector [data-visible="..."] is for).
I hope this clarifies things for you. Feel free to ask if you want me to explain further.
<script>
function testFunction(){
if (x.style.fontSize == "40px"){ //you could use another condition, or a global var here
document.getElementById("test").style.display="none";
}
else{
var x = document.getElementById("test");
x.style.fontSize = "40px";
x.style.color = "blue";
}
}
</script>

How can I make something move in javascript?

I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}

Javascript Zoom on different tabs

I have made a simple zoom in and out function with button as well as mousewheel function. The main concept is to limit the maximum zoom level and minimum zoom level.
I have successfully made it in two ways
BIN 1
BIN 2
But i tried to make this in a tab section with unique ID or by class.
My script
var zoomLevel = 100;
var maxZoomLevel = 150;
var minZoomLevel = 50;
var initW=0,initH=0;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel+=10;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel-=10;
}else{
return;
}
}
img.style.width = (initW*zoomLevel/100)+"px";
img.style.height = (initH*zoomLevel/100)+"px";
img.style.marginLeft = ((initW-img.width)/2) + "px";
img.style.marginTop = ((initH-img.height)/2) + "px";
}
window.onload=function(){
var img=document.getElementById("pic");
initW=img.width;
initH=img.height;
img.onmousewheel=function(e){
e=e||window.event;
if(e.wheelDelta>=120) zoom(1.1);
else zoom(0.9);
};
if(/Firefox/.test(navigator.userAgent)){
img.addEventListener("DOMMouseScroll",function(e){
if(e.detail<0) zoom(1.1);
else if(e.detail>0) zoom(0.9);
e.preventDefault();
},false);
}
};
Here i am getting my element by using GetElementById to access my image tag is there any way to get access all the img tags in other tabs too.
I also tried getElementsbyClassName but its not working it just retrieving the nodeslist.
How can i access all three images here
Current BIN
you need to use different ID's
var img=document.getElementById("pic1");
var img=document.getElementById("pic2");`
You have assigned all three images the same id (id="pic"). You can't do that, ids must be unique.
If you change their ids, (ex: pic, pic2, pic3), and pass that in to your zoom function as an argument, then all the tabs will zoom.
So change the zoom function to look like this:
function zoom(zm, id) {
var img=document.getElementById(id);
...
}
And make your html look like this (just one for an example):
<div id="tabs-2">
<input type="button" value ="-" onClick="zoom(0.9, 'pic2')"/>
<input type="button" value ="+" onClick="zoom(1.1, 'pic2')"/>
<div id="thediv">
<img id="pic2" src="http://stereo-ssc.nascom.nasa.gov/beacon/t0193.jpg"/>
</div>
</div>
Now all three will zoom individually. Here's a jsbin showing it.
But, there's a bug. The variable you use to track the zoom state is being shared between the tabs. This means the "zoom limit" is not really enforced: you can just zoom one tab all the way down, then the next tab all the way up. Repeat this to make any of the images as big or as small as you want. I don't think this is what you want, but I'm going to leave it an exercise for you to fix.

How do I implement press and hold button javascript?

I'm a complete novice, looking for instructions on implementing javascript. I am attempting to replace a YUI slider with buttons and a text field. I am trying to achieve buttons that, when held down, will continue to make the text field increase, preferably at a faster and faster rate. (http://www.blackbird502.com/white.htm)I have this in the java tag in the head:
function holdit(btn, action, start, speedup) {
var t;
var repeat = function () {
action();
t = setTimeout(repeat, start);
start = start / speedup;
}
btn.mousedown = function() {
repeat();
}
btn.mouseup = function () {
clearTimeout(t);
}
/* to use */
holdit(btn, function () { }, 1000, 2);
/* x..1000ms..x..500ms..x..250ms..x */
I have no clue how to implement the press and hold into the following in the body:
<form><input type=button value="UP" class="btn" onClick="javascript:this.form.amount.value++;"><br /><input type=text name=amount value=5 class="text"><br /> <input type=button value="DOWN" class="btn" onClick="javascript:this.form.amount.value--;" ></form>
Is it possible? Thanks.
This code should do everything you're looking for; it's based very loosely on tj111's example. I tried to make it as reusable as possible, and it doesn't need JavaScript mixed in with the HTML.
You do need to add IDs to the buttons (btnUP and btnDOWN) and text field (amount). You can change these IDs in the window.onload statement.
// This function creates a closure and puts a mousedown handler on the element specified in the "button" parameter.
function makeButtonIncrement(button, action, target, initialDelay, multiplier){
var holdTimer, changeValue, timerIsRunning = false, delay = initialDelay;
changeValue = function(){
if(action == "add" && target.value < 1000)
target.value++;
else if(action == "subtract" && target.value > 0)
target.value--;
holdTimer = setTimeout(changeValue, delay);
if(delay > 20) delay = delay * multiplier;
if(!timerIsRunning){
// When the function is first called, it puts an onmouseup handler on the whole document
// that stops the process when the mouse is released. This is important if the user moves
// the cursor off of the button.
document.onmouseup = function(){
clearTimeout(holdTimer);
document.onmouseup = null;
timerIsRunning = false;
delay = initialDelay;
}
timerIsRunning = true;
}
}
button.onmousedown = changeValue;
}
//should only be called after the window/DOM has been loaded
window.onload = function() {
makeButtonIncrement(document.getElementById('btnUP'), "add", document.getElementById('amount'), 500, 0.7);
makeButtonIncrement(document.getElementById('btnDOWN'), "subtract", document.getElementById('amount'), 500, 0.7);
}
This is kind of quick and dirty, but it should give you a start. Basically you want to set up a few initial "constants" that you can play with to get the desired behavior. The initial time between increments is 1000 ms, and on each iteration if become 90% of that (1000, 990, 891, ... 100) and stops getting smaller at 100 ms. You can tweak this factor to get faster or slower acceleration. The rest I believe is pretty close to what I think you were going for. It seems like you were just missing the event assignments. In the window.onload you'll see that i assign the onmouseup, and onmousedown events to functions that just call the increment() or decrement() functions with your initial timeout, or the ClearTimeout() function to stop the counter.
EDIT: I changed this slightly to fix the bug. Now if you move your mouse pointer off the button and release it will stop the counter.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script>
// Fake Constants
var INITIAL_TIME = 1000;
var ACCELERATION = .9;
var MIN_TIME = 100;
// create global variables to hold DOM objects, and timer
var up = null,
down = null,
count = null,
timer = null;
// Increment the counter
function increment (time) {
// decrease timeout by our acceleration factor, unless it's at the minimum
time = (time * ACCELERATION > MIN_TIME) ? (time * ACCELERATION) : MIN_TIME;
count.value ++ ;
// set the timeout for the next round, and pass in the new smaller timeout
timer = setTimeout(
function () {
increment(time);
}, time);
}
// Same as increment only subtracts one instead of adding.
// -- could easily make one function and pass an pos/neg factor instead
function decrement (time) {
time = time * ACCELERATION > MIN_TIME ? (time * ACCELERATION) : MIN_TIME;
count.value --;
timer = setTimeout(
function () {
decrement(time);
}, time);
}
// Initialize the page after all the forms load
window.onload = function () {
// initialization function
// assign DOM objects to our vars for ease of use.
up = document.getElementById('up_btn');
down = document.getElementById('dwn_btn');
count = document.getElementById('count');
// create event handlers for mouse up and down
up.onmousedown = function () {
increment(INITIAL_TIME);
}
down.onmousedown = function () {
decrement(INITIAL_TIME);
}
document.onmouseup = function () {
clearTimeout(timer);
}
}
</script>
</head>
<body>
<!-- Insert your content here -->
<form name="the_form">
<input type="button" value="Up" id="up_btn" /><br />
<input type="button" value="Down" id="dwn_btn" /></br>
<br />
Count:
<input type="text" value="0" id="count" />
</form>
</body>
</html>
The easiest method would be to just add an ID to each of the buttons, then use those to retrieve the elements and add the events.
//should only be called after the window/DOM has been loaded
window.onload = function() {
//the buttons
var btnUP = document.getElementById('btnUP');
var btnDOWN = document.getElementById('btnDOWN');
//the amount
var amount = document.getElementById('amount');
//actions to occur onclick
var upClick = function() {
amount.value++;
}
var downClick = function() {
amount.value--;
}
//assign the actions here
holdit(btnUP, upClick, 1000, 2);
holdit(btnDOWN, downClick, 1000, 2);
}
<form>
<input type=button value="UP" class="btn" id='btnUP'>
<br />
<input type=text name=amount value=5 class="text" id='amount'>
<br />
<input type=button value="DOWN" class="btn" id='btnDOWN'>
</form>
One aspect not to be overlooked is that you're hooking into the onclick event - which happens on a complete click (Mouse key down and key up). It sounds like you would want to listen for another distinct event, http://www.w3schools.com/jsref/jsref_onmousedown.asp'>onMouseDown . I think if you were to then implement some of the other timer based solutions, already given you would get the functionality you're asking for.
Good luck!

Categories