This function decreases OR increases the font size of memedotcomtop and memedotcomtop2 at the same time, once I click to do so. I want to decrease and increase the size of each separately. More specifically you can see on the Image below
I have two text boxes, a plus and a minus button on each
When i want to decrease or increase the size of the text in the first box(memedotcomtop ), it decreases or increases also the size of the text in the second box(memedotcomtop2 )
my code is:
layer.add(memedotcomtop2);
layer.draw();
var textmemeheight2 = stage.getHeight();
layer.draw();
layer.add(memedotcomtop);
layer.draw();
var textmemeheight = stage.getHeight();
layer.draw();
function lowertopsize()
{
if(memefontsize > 10 )
{
memefontsize = memefontsize -1;
memedotcomtop.fontSize(memefontsize);
layer.draw()
}
if(memefontsize2 > 10){
memefontsize2 = memefontsize2 -1;
memedotcomtop2.fontSize(memefontsize2);
layer.draw();
}
}
function increasetopsize()
{
memefontsize2 = memefontsize2 +1;
memedotcomtop2.fontSize(memefontsize2);
memefontsize = memefontsize +1;
memedotcomtop.fontSize(memefontsize);
layer.draw();
}
document.getElementById('meme-top-smaller').addEventListener('click', function() {
lowertopsize();
}, false);
document.getElementById('meme-top-bigger').addEventListener('click', function() {
increasetopsize();
}, false);
document.getElementById('meme-top-smaller2').addEventListener('click', function() {
lowertopsize();
}, false);
document.getElementById('meme-top-bigger2').addEventListener('click', function() {
increasetopsize();
}, false);
I'm using this library: kinetic-v5.0.1.min.js
Try this code.
layer.add(memedotcomtop2);
layer.draw();
var textmemeheight2 = stage.getHeight();
layer.draw();
layer.add(memedotcomtop);
layer.draw();
var textmemeheight = stage.getHeight();
layer.draw();
function lowertopsize() {
if (memefontsize > 10) {
memefontsize = memefontsize - 1;
memedotcomtop.fontSize(memefontsize);
layer.draw()
}
}
function lowertopsize2() {
if (memefontsize2 > 10) {
memefontsize2 = memefontsize2 - 1;
memedotcomtop2.fontSize(memefontsize2);
layer.draw();
}
}
function increasetopsize() {
memefontsize = memefontsize + 1;
memedotcomtop.fontSize(memefontsize);
layer.draw();
}
function increasetopsize2() {
memefontsize2 = memefontsize2 + 1;
memedotcomtop2.fontSize(memefontsize2);
layer.draw();
}
document.getElementById('meme-top-smaller').addEventListener('click', function () {
lowertopsize();
}, false);
document.getElementById('meme-top-bigger').addEventListener('click', function () {
increasetopsize();
}, false);
document.getElementById('meme-top-smaller2').addEventListener('click', function () {
lowertopsize2();
}, false);
document.getElementById('meme-top-bigger2').addEventListener('click', function () {
increasetopsize2();
}, false);
Note:
Create separate functions for each action and don't include memefontsize and memefontsize2 in one function.
Here's a worked example. How you choose to climb through the DOM tree is up to you. The important bit is that you can locate each of the 6 elements that you need to care about - the 4 buttons and the two text containers.
I've also chosen to use the TR elements that contain each row, as an easy means of keeping track of the current level of zoom, ready to be incremented or decremented in response to a button press.
The substantial difference between my approach and the one taken by both yourself and JohnR, is that we only have one function for increments and one for decrements. The function locates the element that triggered it in the DOM, before using this information to alter elements based on their relative position to the original triggering button.
This offers a few advantages:
1) You dont have duplicated code, which is subject to error as changes are made and all copies are updated.
2) You aren't limited in the number of elements on the page you can use this on - there's no need to write new (substantially identical) event handlers.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
// get the table
var tbl = document.getElementById('tgtTbl');
// get each of the row elements
var rows = tbl.getElementsByTagName('tr');
// and make them hold a variable that tracks their current zoom level.
rows[0].zoomLevel = 1;
rows[1].zoomLevel = 1;
// get array of 4 buttons. -,+, -,+
var btns = document.getElementsByTagName('button');
// and connect them to their handlers
btns[0].addEventListener('click', onMinusBtnPressed, false);
btns[1].addEventListener('click', onPlusBtnPressed, false);
btns[2].addEventListener('click', onMinusBtnPressed, false);
btns[3].addEventListener('click', onPlusBtnPressed, false);
}
function onPlusBtnPressed(evt)
{
// determine which button triggered the event
var btn = this;
// determine the TD and TR elements that contain this button
var containingCell = btn.parentNode;
var containingRow = containingCell.parentNode;
// grab the zoom level back from the TR element
var curZoom = containingRow.zoomLevel;
containingRow.zoomLevel += 0.1;
// the text is simply contained within a TD - the first element in the row
var targetCell = containingRow.childNodes[0];
// update the font-size
targetCell.setAttribute('style', 'font-size: ' + (curZoom*100) + '%');
}
function onMinusBtnPressed(evt)
{
var btn = this;
var containingCell = btn.parentNode;
var containingRow = containingCell.parentNode;
var curZoom = containingRow.zoomLevel;
containingRow.zoomLevel -= 0.1;
var targetCell = containingRow.childNodes[0];
targetCell.setAttribute('style', 'font-size: ' + (curZoom*100) + '%');
}
</script>
<style>
</style>
</head>
<body>
<div>
<table id='tgtTbl'>
<tr><td>Your top text</td><td><button>-</button><button>+</button></td></tr>
<tr><td>Your bottom text</td><td><button>-</button><button>+</button></td></tr>
</table>
</div>
</body>
</html>
Related
I am trying to adapt this js code to disable the .click event after you click the button. I am a beginner with js and realy only have a basic understanding. I have tried to use an if statement but that didn't work.
here is the js code:
var sec = ["30% ENTER KEYCODE: Thirty", "25% ENTER KEYCODE: Twenty-five", "20% ENTER KEYCODE: Twenty","15% ENTER KEYCOVE: Fifteen","10% ENTER KEYCODE: Ten","5% EMTER KEYCODE: Five"];
var offset = 30;
//set default degree (360*5)
var degree = 1800;
//number of clicks = 0
var clicks = 0;
$(document).ready(function(){
/*WHEEL SPIN FUNCTION*/
$('#spin').click(function(){
//add 1 every click
clicks ++;
/*multiply the degree by number of clicks
generate random number between 1 - 360,
then add to the new degree*/
var newDegree = degree*clicks;
var extraDegree = Math.floor(Math.random() * 360) + 1;
totalDegree = newDegree+extraDegree;
var colorIndex = Math.ceil(((totalDegree+30) % 360) / 60) -1;
var colorPrev = colorIndex == 0 ? 5 : colorIndex - 1;
var colorNext = colorIndex == 5 ? 0 : colorIndex + 1;
offset = (extraDegree % 60);
var result = sec[colorIndex];
if(offset == 0) {
result ;
} else if (offset <= 30) {
result ;
} else {
result ;
}
$("#answer").html("Answer: " + result);
/*let's make the spin btn to tilt every
time the edge of the section hits
the indicator*/
$('#wheel .sec').each(function(){
var t = $(this);
var noY = 0;
var c = 0;
var n = 700;
var interval = setInterval(function () {
c++;
if (c === n) {
clearInterval(interval);
}
var aoY = t.offset().top;
console.log(aoY);
/*23.7 is the minumum offset number that
each section can get, in a 30 angle degree.
So, if the offset reaches 23.7, then we know
that it has a 30 degree angle and therefore,
exactly aligned with the spin btn*/
if(aoY < 23.89){
console.log('<<<<<<<<');
$('#spin').addClass('spin');
setTimeout(function () {
$('#spin').removeClass('spin');
}, 100);
}
}, 10);
$('#inner-wheel').css({
'transform' : 'rotate(' + totalDegree + 'deg)'
});
noY = t.offset().top;
});
});
});//DOCUMENT READY
here is the original post that I am trying to adapt
https://codepen.io/anon/pen/JGwQva
again I am trying to disable the ability to spin the wheel after you click the spin button.
If you only want to use it once there is a one() method that removes listener after first click
Change:
$('#spin').click(function(){
To
$('#spin').one('click',function(){
There are several hints given by other moderators. Anyways, you may try any of these, lets if this helps.
Simple solution using disabled attribute comes handy.
$(function() {
$('#spin').click(function() {
console.log('clicked..', this);
$(this).prop('disabled', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.one.
$(function() {
$('#spin').one('click', function() {
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.on and $.off.
$(function() {
$('#spin').on('click', function() {
console.log('clicked..', this);
$(this).off('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using some class names.
$(function() {
$('#spin').click(function() {
if ($(this).hasClass('hold')) {
return;
}
$(this).addClass('hold');
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
$('#spin').click(function(){
clicks ++;
if (clicks < 1 ) {
//rest of You code and/or reset clicks variable
}
}
also, change click to $('#spin').on('click',function(){}
var clicks = 0;
$(function () {
$('body').on('click', '#spin', function () {
//
if (clicks > 0) {
return false;
}
// write code here for first click
clicks++;
})
})
I am creating a flowchart using jquery and html which has nodes(circles) and arrows which connect these circles.. two actions need to be done, one is a tooltip action, which will show a particular text when u hover your cursor on particular circle. And the other function is that whenever we click those circles another html page pops up AKA hyperlinks. I have 18 circles and i hav created desired 18 HTML pages. BUt m stuck at hyperlinking. I dont know how to pass these hyperlinks to my Jquery plugin. Below is an attached code for tooltip function
function oncanvasmousemove(evt) {
clearTimeout(timer);
lastTimeMouseMoved = new Date().getTime();
timer = setTimeout(function () {
var currentTime = new Date().getTime();
if (currentTime - lastTimeMouseMoved > 300) {
var mousePos = getMousePos(canvas, evt);
var tC, isMatched = false;
for (c = 0; c < circles.length; c++) {
tC = circles[c];
if (mousePos.DistanceTo(tC.centerX, tC.centerY) < tC.Radius + 5) {
isMatched = true;
break;
}
}
if (isMatched === true) {
$("#tooltip").html(tC.Text).css({
'top': mousePos.Y + canvasoffset.top - 40,
'left': mousePos.X + canvasoffset.left - $("#tooltip").width() / 2
}).show();
} else {
$("#tooltip").hide();
}
}
}, 300);
}
i am attaching a image of the page
You need to give each circle a CSS ID.
For my example, I will just use "#circle-1", "#circle-2" ... "#circle-18".
Also add a CSS class to every circle. For my example I will use ".circle-link".
//On clicking anything with the circle-link class...
$('.circle-link').click(function() {
var link_id = $(this).attr("id"); //Get ID of circle that was clicked
//Get ID number
link_id = link_id.split("-"); //Split the string on the dash/hyphen (returns array)
link_id = link_id[2]; //Get second array element (should be the number)
//Use the above number to determine which link to call
});
Hey there i got this fiddle :
http://jsfiddle.net/5H5Xq/42/
containing this jquery:
function anim(selector) {
$(".images img", selector).first().appendTo($('.images', selector)).fadeOut(2000);
$(".images img", selector).first().fadeIn(2000);
}
// Untuk delay gambarnya
var i = 0, max = 3;
myFunction = function(event){
$(".subbox1").each(function() {anim(this)});
i += 1;
if(i >= max) { i = 0; }
}
var interval = setInterval(myFunction, 5000);
$(".slider").hover(function() {
clearInterval(interval);
var img = $('<img>');
img.attr('src', $(this).attr('data-url'));
$('#newImage').html(img);
$('.images').hide();
return false;
i += 1;
$(".subbox1").each(function() {anim(this)});
});
$(".slider").mouseout(
function (){
$('.images').show();
// $('#newImage').hide();
interval = setInterval(myFunction, 5000);
}
);
It just means:
Every 5 seconds => automatic image-change.
When i hover throw a link => image-change + automatic image change disabled.
What i wanted to add to the automatic image-change:
Depending on the current picture, the -item gets a new background-color..is this possible?
greetings
Sure you can. Just change the background-color css attribute of the element depending on your criteria.
if (*your criteria here*) {
element.css("background-color", "#ff0000");
}
I am using this script to hide and show text however, I want to make the transition smoother but I am not sure how to. Here's a demo of it: http://jsfiddle.net/LnE5U/.
Please help me change it to make it smoother.
hide/show text
<div id="showOrHideDiv" style="display: none">hidden text</div>
<script language="javascript">
function showOrHide()
{
var div = document.getElementById("showOrHideDiv");
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
</script>
Here is an example using jQuery's fadeToggle (a shortcut for a more complicated animate)
// assuming jQuery
$(function () { // on document ready
var div = $('#showOrHideDiv'); // cache <div>
$('#action').click(function () { // on click on the `<a>`
div.fadeToggle(1000); // toggle div visibility over 1 second
});
});
HTML
<a id="action" href="#">hide/show text</a>
<div id="showOrHideDiv" style="display: none;">hidden text</div>
DEMO
An example of a pure JavaScript fader. It looks complicated because I wrote it to support changing direction and duration mid-fade. I'm sure there are still improvements that could be made to it, though.
function generateFader(elem) {
var t = null, goal, current = 0, inProgress = 0;
if (!elem || elem.nodeType !== 1) throw new TypeError('Expecting input of Element');
function visible(e) {
var s = window.getComputedStyle(e);
return +!(s.display === 'none' || s.opacity === '0');
}
function fader(duration) {
var step, aStep, fn, thisID = ++current, vis = visible(elem);
window.clearTimeout(t);
if (inProgress) goal = 1 - goal; // reverse direction if there is one running
else goal = 1 - vis; // else decide direction
if (goal) { // make sure visibility settings correct if hidden
if (!vis) elem.style.opacity = '0';
elem.style.display = 'block';
}
step = goal - +window.getComputedStyle(elem).opacity;
step = 20 * step / duration; // calculate how much to change by every 20ms
if (step >= 0) { // prevent rounding issues
if (step < 0.0001) step = 0.0001;
} else if (step > -0.0001) step = -0.0001;
aStep = Math.abs(step); // cache
fn = function () {
// console.log(step, goal, thisID, current); // debug here
var o = +window.getComputedStyle(elem).opacity;
if (thisID !== current) return;
if (Math.abs(goal - o) < aStep) { // finished
elem.style.opacity = goal;
if (!goal) elem.style.display = 'none';
inProgress = 0;
return;
}
elem.style.opacity = (o + step).toFixed(5);
t = window.setTimeout(fn, 20);
}
inProgress = 1; // mark started
fn(); // start
}
return fader;
}
And using it
window.addEventListener( // this section matches the code above
'load',
function () {
var fader = generateFader(document.getElementById('showOrHideDiv'));
document.getElementById('action').addEventListener(
'click',
function () {
fader(1000);
}
);
}
);
DEMO of this
This is quite simple. I have just made a demo and i used setInterval
Here's how it works
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
}
}, 50);
};
JSFiddle Demo Link
Steps
Create a function that accepts a DOM element
Set the opacity of the element to 1
Create a function that loops every 50ms
If the opacity is greater than 0 -> continue
Take away 0.01 from the opacity
if it's less than 0 the animation is complete and hide it completely
Note this is a really simple example and will need a bit of work
You can use somthing like this
$('.showOrHideDiv').toggle(function() {
$('showOrHideDiv').fadeIn('slow', function() {
//fadeIn or fadeOut, slow or fast, all the stuffs you want to trigger, "a function to execute every odd time the element is clicked," says the [jquery doc][1]
});
}, function() {
//here comes "additional handlers to cycle through after clicks," says the [jquery doc][1]
});
I used OPACITY to make it show/hide. See this Example, Full code (without jQuery):
Click here
<div id="MyMesage" style="display:none; background-color:pink; margin:0 0 0 100px;width:200px;">
blablabla
</div>
<script>
function ShowDiv(name){
//duration of transition (1000 miliseconds equals 1 second)
var duration = 1000;
// how many times should it should be changed in delay duration
var AmountOfActions=100;
var diiv= document.getElementById(name);
diiv.style.opacity = '0'; diiv.style.display = 'block'; var counte=0;
setInterval(function(){counte ++;
if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
},
duration / AmountOfActions);
}
</script>
I followed iConnor solution and works fine but it had a small issue setInterval will not stop after the element be hidden I added stop interval to make it better performance
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
let hidden_process = window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
console.log('1');
clearInterval(hidden_process);
}
}, 50);
};
I am creating a new "whack-a-mole" style game where the children have to hit the correct numbers in accordance to the question. So far it is going really well, I have a timer, count the right and wrong answers and when the game is started I have a number of divs called "characters" that appear in the container randomly at set times.
I have taken away the "play" button and have replaced it with "easy", "medium" and "hard". When a mode is clicked I want the speed to change. The three button share the class "game_settings"
Here is the code that makes deals with the animation
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function scramble() {
var children = $('#container').children();
var randomId = randomFromTo(1, children.length);
moveRandom("char" + randomId);
}
var currentMoving = [];
function moveRandom(id) {
// If this one's already animating, skip it
if ($.inArray(id, currentMoving) !== -1) {
return;
}
// Mark this one as animating
currentMoving.push(id);
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var bWidth = $('#' + id).width();
var bHeight = $('#' + id).css('top', '395px').fadeIn(100).animate({
'top': '-55px'
}, 6000).fadeOut(100);
maxWidth = cPos.left + cWidth - bWidth;
minWidth = cPos.left;
newWidth = randomFromTo(minWidth, maxWidth);
$('#' + id).css({
left: newWidth
}).fadeIn(1000, function () {
setTimeout(function () {
$('#' + id).fadeOut(1000);
// Mark this as no longer animating
var ix = $.inArray(id, currentMoving);
if (ix !== -1) {
currentMoving.splice(ix, 1);
}
window.cont++;
}, 1000);
});
}
How would I make it so that these settings change in accordance the the difficulty pressed at the beginning?
Fiddle: http://jsfiddle.net/pUwKb/53/
Your buttons do not share the class 'game_ettings', they are inside the div with a class 'game_settings', so the game starts also in case you click between the buttons. modify it like this:
// remove this line
$(".game_settings").find('input').click(
// replace it with...
var AnimationSpeed = 6000;
$(".game_settings").find('input').click(function () {
// here you could set a different timer value for each variant
// or simply send the classname to startplay and handle the
// settings there.
switch($(this).attr('class')) {
case 'easy':
AnimationSpeed = 6000;
break;
case 'medium':
AnimationSpeed = 3000;
break;
case 'hard':
AnimationSpeed = 1000;
break;
}
startplay();
});
In your timer function remove the line:
$("#btnstart").bind("click", startplay);
And in your function moveRandom you use the AnitmationSpeed:
var bHeight = $('#' + id).css('top', '395px').
fadeIn(100).animate({'top': '-55px'}, AnimationSpeed).
fadeOut(100);
You find a working demo here.
What I think you want to do is set the timeInterval according to the game difficulty. This is how I think you might get it to work.
Changes to be made:
html:
//Change
<div class="game_settings">
<div><input class="easy" type="button" value="Easy"></div>
<div><input class="medium" type="button" value="Medium"></div>
<div><input class="hard" type="button" value="Hard"></div>
</div>
//To
<div class="game_settings">
<div><input class="game-speed" id="easy" type="button" value="Easy"></div>
<div><input class="game-speed" id="medium" type="button" value="Medium"></div>
<div><input class="game-speed" id="hard" type="button" value="Hard"></div>
</div>
Sript:
//Change
$(".game_settings").click(function () {
startplay();
});
//To
$(".game-speed").click(function () {
startplay($(this).attr('id'));
});
//Change in startPlay()
startPlay()
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 500);
//To
startplay(speed_check) // As it is now expecting a variable
if(speed_check == 'easy'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 2000);
}
else if(speed_check == 'medium'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 1000);
}
else if(speed_check == 'hard'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 400);
}
else{
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 1000);
}
Set the time intervals as you like.
Note: This is just an idea what it should be like. You can ofcourse make it more efficient as you know your code better that anyone else.
In DotNet you need to "stop" the storyboard and restart with speed modification.
Dim sb as Storyboard = ctype(Me.FindRessources("Storyboard1"), Storyboard)
sb.Stop
Select Case Level
Case "easy": sb.SpeedRatio = 0.75
Case "medium": sb.SpeedRatio = 1
Case "hard": sb.SpeedRatio = 2.0
End Select
sb.Begin
Perhaps it is the same in JavaScript?