adding html within var string? - javascript

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);
}

Related

JS automatic transfer codes needs discussion

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;

Stop incremental counter and disable interaction

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/

(Javascript) Script won't count just once, perhaps not recognizing variable?

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

javascript - replace text with tags

i do not know much about javascript searched long, but didn't get the reslut i need.
i want to replace on page load this
<p>---SOMERANDOMTEXT:::</p>
with
<strong>SOMERANDOMTEXT</strong>
played with this an many other snippets..
<script type="text/javascript">
window.onload = function() {
function myscript() {
input = '---';
output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
}
</script>
Here is the fast and fool proof way of replacing <p> tags with <strong> tags:
var ps = document.getElementsByTagName('p');
for (var i = ps.length; i--;) {
var strong = document.createElement('strong'),
p = ps[i];
while (p.firstChild) {
strong.appendChild(p.firstChild);
}
p.parentNode.insertBefore(strong, p);
p.parentNode.removeChild(p);
}
If you need to change the text accordingly, place something like that in the while loop:
if (p.firstChild.nodeType === 3) {
p.firstChild.nodeValue = p.firstChild.nodeValue.replace(/[-:]{3}/g, '');
}
DEMO: http://jsfiddle.net/5m9Qm/1/
You need to call your myscript function like this -
window.onload = function() {
myscript();
}
function myscript() {
var input = '---';
var output='New Text';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
You are declaring a function myscript but never invoking it. Try this (untested) code:
<script>
window.onload = function(){
var p = document.querySelector('p');
var strong = document.createElement('strong');
strong.innerHTML = 'replaced';
p.parentNode.replaceChild(strong,p);
})
</script>
Note this requires modern browsers.
You can use a regex.
Try:
output = document.body.innerText.replace(/[-:]{3}/g, '');
document.body.innerHTML = document.body.innerHTML.replace(/<p>---.*:::<\/p>/, '<strong>' + output + '</strong>');
DEMO

Javascript Text effect

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.

Categories

Resources