How to store a variable in an Array using AngularJS? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there any function that i can use?
Or i need to create one? Or can i use push? It is modified script from this page:
http://code-maven.com/automatic-counter-using-angularjs
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
angular.module('CounterApp', [])
.controller('CounterController', function($scope, $timeout) {
var timer;
$scope.stored = [];
$scope.counter= 0;
$scope.stopCounter = function() {
$timeout.cancel(timer);
timer = null;
};
$scope.startCounter = function() {
if (timer === null) {
updateCounter();
}
$scope.stored.push(counter);
};
$scope.pushedVariable = function() {
$scope.stored.push(counter);
};
var updateCounter = function() {
$scope.counter++;
timer = $timeout(updateCounter, 1000);
};
$timeout.cancel(timer);
timer = null;
});
</script>
<div ng-app="CounterApp">
<div ng-controller="CounterController">
<button ng-click="stopCounter()">Stop</button>
<button ng-click="startCounter()">Start</button>
<button ng-click="pushedVariable()">Push</button>
{{counter}}
<p>Stored Variable 1: {{stored[0]}}</p>
<p>Stored Variable 2: {{stored[1]}}</p>
</div>
</div>

You just need to use $scope.stored.push($scope.counter); in your function instead of your current $scope.stored.push(counter); which is an undefined variable.

function(obj) {
var str = [];
for(var val in obj)
str.push(encodeURIComponent(val) + "=" + encodeURIComponent(obj[val]));
}
Where "obj" is your object.

Related

How hide javascript on specific page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I have a javascript code for our online chat that we use in our application. But I need this code to not appear on a specific page, eg domain/X1XY.
Can you advise me how I can write this in the main code that is called on each of our pages?
<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = '123456789';
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='https://www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
If the URL of the page is unique, then you can use it to conditionally run the JavaScript using the document object's URL property:
<script type="text/javascript">
if (document.URL !== 'https://<your URL here>') {
var _smartsupp = _smartsupp || {};
_smartsupp.key = '123456789';
window.smartsupp ||
(function (d) {
var s,
c,
o = (smartsupp = function () {
o._.push(arguments);
});
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.src = 'https://www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);
}
</script>
Hope this helps.
if (window.location.pathname !== '/X1XY') { // your code here }

How do I replace all URLs of a target domain in html code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I'm trying to replace all HREF with domain1.com with the URL described in his title (if it has a title).
var els = document.getElementsByTagName('a'),
for (els in url) {
if (url.includes(domain1)); {
var titulo = url.attr('title');
var enlace = url.attr('href');
url.replace(enlace, titulo);
}
}
<p style="margin:40px;" line-height:2px;=""><img src="https://www.domain1.com/738956_1.jpg" data-width="1070" data-height="1387" data-image="738956-sanKH" alt="738956-sanKH.jpg">XS texto<br>
<img src="https://www.domain1.com/738956_1.jpg" data-width="1077" data-height="1693" data-image="738956-iMkWh" alt="738956-iMkWh.jpg">S texto</p>
I'm a beginner in javascript. Sure have a lot of format mistakes. Thanks in advance
Here is a tested JavaScript code, replace the for..of with for..in if you want to support Internet Explorer browser.
var domain1 = 'domain1.com';
var els = document.getElementsByTagName('a');
for (var url of els) {
var title = url.getAttribute('title');
if (title && url.getAttribute('href').search(domain1) !== -1) {
url.setAttribute('href', title);
}
}
If your DOM is having all the links after document load, then you can do this:
window.onload = bindEvents;
function bindEvents() {
// replace href with title
bindAnchorTitleAsHref();
}
function bindAnchorTitleAsHref() {
const els = document.getElementsByTagName('a');
for (let i = 0; i < els.length; i += 1) {
const title = els[i].getAttribute('title');
const href = els[i].getAttribute('href')
els[i].setAttribute('href', title);
console.log('New Href set :', els[i].getAttribute('href'), 'instead of', href);
}
}
<a
href="https://www.domian1.com/plants"
title="https://www.newdomain.com/test1"
target="_blank"
rel="nofollow noopener"
>
texto
</a>
If you just want to update the domain of the link, then you can use the URL class:
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('a[title]').forEach(el => {
const href = new URL(el.href);
if ((/[\^\.]domain1.com$/i).test(href.host)) {
const title = new URL(el.title);
href.host = title.host;
el.href = href.toString();
}
});
});
<p style="margin:40px;" line-height:2px;=""><img src="https://www.domain1.com/738956_1.jpg" data-width="1070" data-height="1387" data-image="738956-sanKH" alt="738956-sanKH.jpg">XS texto<br>
<img src="https://www.domain1.com/738956_1.jpg" data-width="1077" data-height="1693" data-image="738956-iMkWh" alt="738956-iMkWh.jpg">S texto</p>

How to place a variable inside getElementbyId() that changes during each repetition of a loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want something similar to f" {variable} " of python
Ive tried
function press()
{
for(var i=0; i<4; i++)
{
if(!document.getElementById('ip'+i).value)
{
alert("error");
break;
}
}
but it didnt work.
I want something similar to f" {variable} " of python
template strings ${variable}
In JavaScript you can use template strings
The usage is
` ${variable} `
document.getElementById('btn').addEventListener('click', press)
function press() {
for (var i = 0; i < 4; i++) {
if (!document.getElementById(`ip${i}`).value) {
alert("error");
break;
}
}
}
<input id="ip0"/>
<input id="ip1"/>
<input id="ip2"/>
<input id="ip3"/>
<button id="btn">Click</button>

Need Help: Make the quiz random [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble making the questions random. If you could help, it would be awesome!
(If you have spear time; I've been given the task to mark correct answer with a green feather and wrong answers with red feather, for instance, if you get 3 correct and 2 wrong. It will show 3 green feathers and 2 red feathers as score.) Thank you!
<script type="text/javascript">
var questions = [
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'],
['firstcar.gif','0'],
['secondcar.gif','1'],
['thirdcar.gif','2'] // Note: no comma after last entry
];
var qNo = 0;
var correct = 0;
var cnt = 0;
function NextQuestion(response) {
if ((qNo < questions.length) && (response == questions[qNo][1])) {
correct++;
}
document.getElementById('score').innerHTML = 'Correct ' + correct + ' of 6 questions';
qNo++;
if (qNo < questions.length) {
document.getElementById('Pic').src = questions[qNo][0];
cnt++;
}else{
alert('Quiz is done. You got ' + correct + ' points!');
}
}
onload = function() {
document.getElementById('Pic').src = questions[0][0];
}
</script>
</head>
<body>
<div align="center">
<h1>Which car is it?</h1>
<img src="" id="Pic" height="200" width="250">
<p>Is it
<button onclick="NextQuestion('0')">Red</button>
<button onclick="NextQuestion('1')">Black</button>
<button onclick="NextQuestion('2')">Yellow</button>
<p>Your score: <br>
<span id="score"></span>
</div>
</body>
</html>
Well, your questions are in an array. So what you should be researching is how to randomise the order of an array.
questions.sort(function() { return Math.floor(Math.random() * 2); });

How short can this script be and still achieve the same thing - display a message "loading.." followed by an extra period every 1 second for 7 seconds [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
<script>
var dot = ".";
var counter = 0;
var message = "Loading Page";
function writeLoadingMessage(){
if (counter > 6) return;
setTimeout('writeMessage();',1000);
}
function writeMessage(){
document.getElementById('loadingMessageSpan').innerHTML = message + dot;
message += dot
counter++
writeLoadingMessage();
}
</script>
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan"></span>
<SCRIPT>writeLoadingMessage();</SCRIPT>
</BODY>
(function(){var i=6,a=setInterval(function(){document.getElementById('loadingMessageSpan').innerHTML+=".";!i--&&clearInterval(a);},1E3)})()
You will need to have Loading already in your span tag. As a note it is pointless to worry about getting it this small though. Also, the page will will have to be already loaded.
If you want it shorter: http://jsfiddle.net/pimvdb/wBFSy/.
<script>
var counter = 0;
function writeMessage() {
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter < 7) {
setTimeout(writeMessage, 1000);
}
}
window.onload = writeMessage;
</script>
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
</body>
Minifying also helps :)
var a=0;function b(){document.getElementById("loadingMessageSpan").innerHTML+=".";++a<7&&setTimeout(b,1E3)}window.onload=b
1) User setInterval instead.
2) Just set the message once and append . to end
3) Put all the js at the bottom
<body>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script type="text/javascript">
var counter = 0;
var id = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter>6) {
clearInterval(id);
}
}, 1000);
</script>
</body>
If you really want it short you can go this route:
<BODY>
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
<script>
var counter = 0;
var interval = setInterval(function(){
document.getElementById('loadingMessageSpan').innerHTML += ".";
if(++counter > 6)
clearInterval(interval);
},1000)
</script>
</BODY>
http://jsfiddle.net/kc3fb/2/

Categories