I am trying to create a JS plugin, which will take in a string as input, and the string will slowly lose characters, one from each end at a time, and eventually vanish (string length = 0).
This is the code I have written so far :
var start=0;
var finish=0;
$.fn.scramble = function(){
$(this).each(function(){
$element = $(this);
$inputString = $element.text().trim();
finish = $inputString.length;
vanish($inputString.substring(start++, finish--));
})
}
vanish = function($inputString){
console.log($inputString);
$stringLength = $inputString.length;
console.log($stringLength);
if($stringLength <= 0)
return 0;
setTimeout(function(){
vanish($inputString.substring(start++, finish--));
}, 1000);
}
I am giving it a sample input, "Samples". The expected output is "ample", "mpl", "p". But instead it returns "ample", "ple".
Surely, I am doing something wrong here, but I am unable to figure it out. Kindly help :)
Here's a fiddle set up : http://jsfiddle.net/v6KKM/
Consider changing finish = $inputString.length; to finish = $inputString.length - 1;
$.fn.scramble = function(){
$(this).each(function(){
$element = $(this);
$inputString = $element.text().trim();
finish = $inputString.length;
vanish($inputString.slice(1, -1));
})
}
vanish = function($inputString){
console.log($inputString);
$stringLength = $inputString.length;
// console.log($stringLength);
if($stringLength <= 0)
return 0;
setTimeout(function(){
vanish($inputString.slice(1, -1));
}, 1000);
}
Maybe this what you want.
You can compare 'substring' and 'slice'. I hope this does help.
You can obtain the same result in easier way using arrays and recursive function
Fiddle
all code you need is
<script type="text/javascript">
$(document).ready(function(){
$.fn.scramble = function(){
var str=$(this).text()
function recursor(str){
newS=''
if(str.length>=3){
var arr=str.split('')
arr.pop()
arr.shift()
for(a=0;a<arr.length;a++){newS+=arr[a]}
$('#text').append(' '+newS)
setTimeout(function() { recursor(newS) },1000)
}
}
recursor(str)
}
$('#sc').click(function(){
$('#text').scramble()
})
})
</script>
or (brobably better) you ca use substring Fiddle2 and you'll obtain a more compact code
<script type="text/javascript">
$(document).ready(function(){
$.fn.scramble = function(){
var str=$(this).text()
function recursor(str){
if(str.length>=3){
var result = str.substring(1, str.length-1);
$('#text').append(' '+result)
setTimeout(function() { recursor(result) },1000)
}
}
recursor(str)
}
$('#sc').click(function(){
$('#text').scramble()
})
})
</script>
this solution does not suit your needs, i apologize for making you lose time.
Related
I wrote a script in Javascript with 2 functions.
Die first shows random pictures in an random position
This works fine
The second script has to "clear up" everthing and put everything back to the Startposition.
My script at this time:
function clearPics(){
$("img[class^='mapic']").attr('src','empty100.jpg');
$("img[class^='mapic']").attr("title",'');
$("img[class^='mapic']").attr("alt",'');
}
function makePics(){
// 1 Step take 5 different Pics
var MAAuswahlArr = [];
var AnzahlAnzeige = 5;
var lauf = AnzahlAnzeige
while (lauf > 0){
var testvar = getRandomInt(0,MAArr.length-1);
if (contains.call(MAAuswahlArr, testvar)){
}else{
MAAuswahlArr.push(testvar);
lauf--;
}
}
// 2 Step get 5 of 10 different positions
var BildanzahlMax = 10
var BildanzahlArr = [];
var BildPositionenbesetzt = 5;
lauf = BildPositionenbesetzt;
while (lauf > 0){
var testvar = getRandomInt(0,BildanzahlMax);
if (contains.call(BildanzahlArr, testvar)){
}else{
BildanzahlArr.push(testvar);
lauf--;
}
}
// 3 step: take 5 Pics an put ist in the src the alt and title Tags
lauf = BildanzahlMax;
while (lauf > 0){
var className = "mapic"+lauf;
if (contains.call(BildanzahlArr, lauf)){
$('.'+className).attr('src',MAArr[lauf-1][2]);
$('.'+className).attr("title",MAArr[lauf-1][1]);
$('.'+className).attr("alt",MAArr[lauf-1][0]);
}
lauf--;
}
// 4. step: make the Pics Hover
$("img[class^='mapic']").hover(function() {
var maName = $(this).attr("title");
var mafunktion = $(this).attr("alt");
$('.matextblock').html("<h3> Unser Team</h3> <p class='maName'>"+mafunktion+"</p><p class='maFunktion'>"+maName+"</p>");
console.log('huhu rein');
}, function() {
$('.matextblock').html('');
});
return true;
}
$(document).ready(function() {
setInterval(function(){
var done = makePics();
console.log(done);
if (done){
clearPics();
//console.log('clear');
}else{
done = false;
}
},2000);
});
How can I run the script to
a) make the Picture
b) wait 5 or n seconds
c) clear up
and go back to a) ?
Your done variable should be declared outside of the anonymous function executed by setInterval. Right now it is redeclared every time the function fires, so the if/else branch is useless.
Exampel code:
$(function() {
var pictureShown = false;
var interval = 5000;
setInterval(function () {
if(pictureShown) {
clearPics();
} else {
makePics();
pictureShown = true;
//OR, if makePics returns true:
//pictureShown = makePics();
}
}, interval);
});
Edit: I adapted your setInterval code to make it work, but the whole setup could be much simplified - see Adder's response.
Thank Folks I got it
this is my Code witch workls fine for me.
Ich change the positio for the clearPics funtion.
So I do not have to wait 5 Seconds to the next Pictures :-?
var done = false;
var interval = 5000;
$(document).ready(function() {
setInterval(function(){
//done = makePics();
if (done){
done = false;
}else{
clearPics();
done = makePics();
}
console.log(done);
},interval);
});
I think the code can be simplified. As far as I can tell from the info on the functions you gave out.
$(document).ready(function() {
makePics();
setInterval(function(){
clearPics();
var done = makePics();
},2000);
}
This will clear the pics first, and then redisplay a new set of Pics with makePics, every 2000 ms.
I got a piece of code that can help me redirect to a page automatically after a period of time. However, it doesn't work.
Could anybody take a look at it,and, if possible, modify it? Thanks!!
<body>
.......
<script>
var dizhi = "";
function get() {
var _el = document.querySelectorAll('#lianjie');
var len = _el.length();
if (len > 0) {
dizhi = _el[0].href;
}
}
onload = function() {
get();
setTimeout(function() {
location.href = dizhi;
}, 1000);
}
</script>
</body>
length is a property and not a method, so:
var len = _el.length();
should actually be:
var len = _el.length;
I am trying to get the counter to stop at 0 and when it does the entire div is unclickable/disable interaction.
There is a link in the middle. So when i click 3 times I want it to be un-clickable.
edit:also it doesn't need to use Knockout. any approach, if more simple is fine.
What would be the best approach?
Fiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
Simply try adding this line
if (this.numberOfClicks() > 0)
Before
this.numberOfClicks(this.numberOfClicks() - 1);
We'll get something like that:
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
if (this.numberOfClicks() > 0)
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
See Fiddle
A bit late but give a look to my solution because I simplified a lot your code and I think you can get some value from it (for example the use of var self = this which is a best practice).
The idea behind my solution is very simple:
1) Show or hide the link or a normal text with respect to your hasClickedTooManyTimes computed variable.
empty link
<p data-bind='if: hasClickedTooManyTimes'>empty link</p>
2) Simply block the click on div if hasClickedTooManyTimes is true.
self.registerClick = function() {
if(!self.hasClickedTooManyTimes()){
self.numberOfClicks(this.numberOfClicks() - 1);
}
};
Check the Fiddle!
Let me know if this was useful to you!
Just disable the link when your count is done:
First add an id to your link:
<a id="a1" href=#> <p>empty link</p> </a>
Next disable that id when the time is right like this in your javascript:
this.hasClickedTooManyTimes = ko.computed(function() {
if (this.numberOfClicks() < 0) {
$('#a1').attr('disabled', 'disabled'); // <--- disable it
}
return this.numberOfClicks() <= 0;
}, this);
Take a look at the fiddle for JS code, stackoverflow is not validating my code section for the JS content.
HTML
<body>
<div>You have teste clicks!</div>
<div id="demo"></div>
</body>
JS
var btnObserver = (function() {
var me= this;
var clickleft = 3;
var registerClick = function() {
if(clickleft > 0) {
clickleft--;
}
};
var isCLickable = function() {
console.log(clickleft);
return clickleft !== 0;
};
return {
registerClick: registerClick,
isCLickable: isCLickable
}
})();
document.getElementById("mybtn").addEventListener("click", function(){
var message= "Hello World";
btnObserver.registerClick();
if(!btnObserver.isCLickable()) {
message= "X Blocked!";
// return false or do anything you need here
}
document.getElementById("demo").innerHTML = message;
});
Fiddle: http://jsfiddle.net/qkafjmdp/
I'm sure this is a super easy fix and I just can't see it..
I have a play button and I only want it to write to database (inc playcount) only when it's clicked the first time.
Any idea why this doesn't work? This result counts every click, and if I do if countonce = 0 and declare at beginning as 0 it won't count any clicks. Am I misunderstanding javascript?
<div id="left-05-play_">
<script type="text/javascript">
var currsong = 1;
var playcountadd = document.getElementById('left-05-play_');
playcountadd.onclick = function() {
if (countonce != 1) {
$.post( "php/songadd.php", { addsong: "1", } );
var countonce = 1;
} }
</script>
</div>
Thank-you for taking the time to read this question.
This should do the trick.
var currsong = 1;
var songadded = false;
var playcountadd = document.getElementById('left-05-play_');
playcountadd.onclick = function() {
if (!songadded) {
$.post( "php/songadd.php", { addsong: "1", } );
songadded = true;
}
}
Changed countonce to songadded
Moved songadded out of onclick function
Changed songadded to boolean logic
Check whether songadded=false before proceeding with AJAX post
Say I have
var b = 'I am a JavaScript hacker.'
How can I do this ?
var b = 'I am a JavaScript hacker.'
Is this dooable ?
I thought the question was clear. Apologies if it wasnt.
Fiddle here http://jsfiddle.net/ozzy/vWYQ2/
$(function() {
var mem = $("#TA").html();
$("#TA").hover(function() {
$(this).stop().html( 'I am a JavaScript hacker.' );
}, function() {
$(this).stop().html( mem );
});
});
I think you want something like this
My code
Edited: Due to the flickering issue.
um... yes? that will give you a variable named b which holds 'I am a JavaScript hacker.'
Code from http://jsfiddle.net/vWYQ2/2/, this removes the hyperlink once mouse is out.
HTML
<div id="TA" onmousemove="changetext();" onmouseout="restore();">I am a JavaScript hacker.</div>
JavaScript
var originalBlock = document.getElementById("TA").innerHTML;
var timer;
function changetext()
{
var id = document.getElementById("TA");
if(originalBlock == null) originalBlock= id.innerHTML;
var text = id.innerHTML;
id.innerHTML = text.replace("JavaScript hacker", "<a href='foo.php'>JavaScript hacker</a>");
if(timer != null)
clearTimeout(timer);
}
function restore()
{
timer = setTimeout(function()
{
document.getElementById("TA").innerHTML = originalBlock;
}, 1000);
}