JavaScript using indexOf and lastIndexOf to put setattribuit - javascript

I want to use indexOf() and lastIndex() to add attributes by setAttribute after customizing the URL.
I try this code but not working:
<!DOCTYPE html>
<html>
<head>
<style>
#two {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 50px;
}
</style>
<title></title>
</head>
<body>
<select onchange="check()" id="selectbox" name="">
<option hidden value="empty"></option>
<option value="first">1</option>
<option value="second">2</option>
</select>
<div id="two">
<div id="de6854">
<div style="width: 100%;height: 100%">
<iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100" style="width: 100%; height: 100%">
</iframe>
<iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100" style="width: 100%; height: 100%">
</iframe>
</div>
</div>
</div>
</body>
<script>
function check(){
var val = document.getElementById("selectbox").value
var pic = document.querySelectorAll("#two iframe")
var s = val.substring(0, val.indexOf('?resize='));
var ss= val.substring(val.lastIndexOf(',10'));
var f = s + ?resize= + '400' + ss;
var s = s + ?resize= + '500' + ss;
if(val==="first"){
pic.setAttribute('src','f')
} else if(val==="second"){
pic.setAttribute('src','s')
}
}
</script>
</html>
Any one can find solution of that problem:
I test write that code in JavaScript and running good:
var s = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
s = s.substring(0, s.indexOf('?resize='));
document.write(s);
document.write('<br>');
document.write('<br>');
var ss = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
ss = ss.substring(ss.lastIndexOf(',10'));
document.write(ss);
document.write('<br>');
document.write('<br>');
rr = s+"?resize="+"500"+ss
document.write(rr);
this code give result: https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=500,100
change 200 and add 500.
second code after some answers:
not the ID in frame in changed every load page, like that: <iframe id="3ad34"
code:
<!DOCTYPE html>
<html>
<head>
<style>
#twoposition {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 50px;
}
</style>
<title></title>
</head>
<body>
<select onchange="check()" id="selectbox" name="">
<option hidden value="empty"></option>
<option value="firstSize">1</option>
<option value="secondSize">2</option>
</select>
<div id="two">
<div id="de6854">
<div style="width: 100%;height: 100%">
<iframe id="4526d" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
</iframe>
<iframe id="3ad34" src="https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100">
</iframe>
</div>
</div>
</div>
</body>
<script>
function check() {
var val = document.getElementById("selectbox").value
var pic = document.querySelectorAll("#two iframe")
var aa = pic.getAttribute('src')
const url = new URL(aa);
url.searchParams.set('resize', '500,200');
if(val === "firstSize") {
pic.setAttribute('src', ff)
}
else if(val === "secondSize") {
pic.setAttribute('src', ff)
}
}
</script>
</html>

You can simply use an URL() constructor and set the URL.searchParams on it as needed.
const inputUrl = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100';
const url = new URL(inputUrl);
url.searchParams.set('resize', '500,200');
console.log(url);
Example assigning it to an attribute.
function addImgWithSize(inputUrl, width=300, height=200){
const url = new URL(inputUrl);
url.searchParams.set('resize', [width, height]);
// assigning it to the 'src' attribute
const img = document.createElement('img');
img.src = url;
document.body.append(img);
}
const exampleUrl = 'https://www.ask.com/wp-content/uploads/sites/3/2022/02/PowerOfDogPromo.jpeg?resize=200,100'
addImgWithSize(exampleUrl, 500, 200)
addImgWithSize(exampleUrl, 30, 20)

Related

why does my innerHTML vars don't add correct?

Ok so it does add, but not right
So my vars think that they are text but I want just the nums, so I can add them together.
How do I do this?
a fiddle to see whats so wrong
<html>
<head>
<title>Nose Clicker</title>
<style>
body{
background-image:url("https://i.pinimg.com/originals/66/27/70/6627703d20110ad2e8877fab5fc102b9.jpg");
}
#root-SuperGloabalVar1{
color: red;
font-size: 150px;
padding: 0px;
}
#var-wrapper{
opacity: 0%;
}
</style>
</head>
<body>
<div id = 'var-wrapper'>
<h1 class = 'vars' id = 'perclick'>
<---here is the first addend--->
1
</h1>
</div>
<---here the second one--->
<h1 id = 'root-SuperGloabalVar1'>0</h1>
<img onclick = '
<---get number 1--->
var v = getElementById("root-SuperGloabalVar1");
<---get number 2--->
var a = getElementById("perclick");
<---adding--->
var w = v.innerHTML+=a.innerHTML;
<---replacing and then it shows "01"--->
v.innerHTML(parrseint(a.innerHTML + v));
'
src = 'https://www.pngitem.com/pimgs/m/155-1559954_cartoon-nose-images-cartoon-nose- image-png-transparent.png'>
</body>
</html>
I didn't completely understand your question can you explain it a bit more and detailed but if you want to parse text into number then use
var x = a.innerHTML;
Number(x)
Edit:
And a proper way to use number increment and display it is like this:
(you don't need to save your integer in an element you can use a javascript variable)
let clicks = 0;
function countClicks() {
clicks++;
const display = document.getElementById("display");
display.innerHTML = clicks;
}
<!DOCTYPE html>
<html lang="en">
<body>
<div style="background: red; width: 100px; height: 100px;" onclick="countClicks();">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>
</html>
Example to use in onclick callback:
<body>
<script>var clicks = 0;</script>
<div style="background: red; width: 100px; height: 100px;"
onclick=
"
clicks++;
const display = document.getElementById('display');
display.innerHTML = clicks;
">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>

Problem with image 'rotations' within a div element

I'm using the code below to create a 'rotation' of images for display on a website. I wish for the images to display within a 'div' element...and i'm having trouble accomplishing that. It seems the problem is when I attempt to set each image as the 'background image' for the element (the line that reads "document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";). Only the initial image displays, without any 'rotation' of other images. Any help appreciated, this is becoming very frustrating.
<!DOCTYPE html>
<html>
<title>test page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
div.rotation {
height: 256px;
width: 100%;
padding: 0px;
background-color: powderblue;
border-style: solid;
border-width: 5px;
border-radius: 25px;
}
</style>
</head>
<body>
<div class="w3-quarter">
<div class="w3-padding-small">
<div class="w3-center">
<div class="rotation">
<p>
<img src='images/rotation/LA_Panel.png' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/McCulloch_256.png' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/MO_Panel.png' id='rotateImg2' style='display:none;' alt='image rotation' />
<img src='images/rotation/Rommel.png' id='rotateImg3' style='display:none;' alt='image rotation' />
</p>
</div>
</div>
</div>
</div>
</body>
</html>
<script type='text/javascript'>
var rotation = function () {
var currentImage,
images = [],
ImgName = [],
count,
hideImages,
showImage,
fn;
count = (function () {
// Figure out how many images we have on the rotation
var x = 0;
while (document.getElementById('rotateImg' + (x + 1).toString())) {
images[x] = document.getElementById('rotateImg' + x.toString());
ImgName[x] = document.getElementById('rotateImg' + x.toString()).src;
x++;
}
return images.length;
})();
hideImages = function () {
// Hide all the images
for (var i = 0; i < count; i++) {
images[i].style.display = 'none';
}
};
showImage = function (number) {
document.getElementById("rotation").style.backgroundImage = "url(toString(ImgName[number]))";
images[number].style.display = 'block';
};
fn = {};
fn.setupRotation = function () {
// Show the first image
currentImage = 0;
showImage(currentImage);
// Start the rotation
var interval = setInterval(rotation.advanceRotation, 4000);
};
fn.advanceRotation = function () {
if (currentImage + 1 == count)
currentImage = 0;
else
currentImage++;
hideImages();
showImage(currentImage);
};
return fn;
} ();
rotation.setupRotation();
</script>
One thought might be to pluck off the first child and slam him to the end of the line.
let images = document.querySelector('#images');
setInterval(() => {
let el = images.removeChild(images.childNodes[0]);
images.appendChild(el);
}, 1000);
#images {
font-size: 0;
}
.img {
display: inline-block;
width: 30px;
height: 30px;
}
<div id="images">
<div class="img" style="background-color: red"></div>
<div class="img" style="background-color: orange"></div>
<div class="img" style="background-color: yellow"></div>
<div class="img" style="background-color: green"></div>
<div class="img" style="background-color: blue"></div>
</div>

Changing Iframes HTML

I need a script to change the iframes src every certain amount of seconds. The time between the change is different between each one.
Example:
Page Loads
Google.com is loaded.
15 seconds later
Yahoo.com is loaded.
37 seconds later
Ask.com is loaded.
12 seconds later
Dogpile.com is loaded.
and so on and so forth.
I've tried that:
<html>
<head>
<meta charset="utf-8" />
<title>Monitor PresidĂȘncia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/1.11.8/semantic.min.js"></script>
</head>
<body>
<div style="width: 100%; display: flex;">
<div class="ui teal progress" data-percent="0" id="example1" style="width: 90%;margin-bottom: 0px">
<div class="bar"></div>
</div>
<div class="ui icon buttons" style="width: 10%">
<button class="ui button" style="width: 25%" onclick="menos_um()">
<i class="left chevron icon"></i>
</button>
<button class="ui button " style="width: 25%" onclick="inicia()">
<i class="play icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="para_aplicacao()">
<i class="pause icon"></i>
</button>
<button class="ui button" style="width: 25%" onclick="mais_um()">
<i class="right chevron icon"></i>
</button>
</div>
</div>
<iframe id="envase" class="frame_mon" style="width: 100%;height: 100%;" src="www.google.com.br"></iframe>
<iframe id="frete_hl" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.yahoo.com.br"></iframe>
<iframe id="frete_hl_acum" class="frame_mon" style="width: 100%;height: 100%;display: none;" src="www.terra.com.br"></iframe>
</body>
<script>
var arr_monitores = ["envase", "frete_hl", "frete_hl_acum"];
var num_monitor = 0;
var progresso = 0;
var myVar;
var setintervalatualizaframe;
function mais_um() {
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";*/
progresso = 100;
myStopFunction();
inicia();
/* if (num_monitor === 2) {
num_monitor = 0;
} else {
num_monitor++;
}*/
};
function menos_um() {
//progresso = 100;
if (num_monitor === 0) {
num_monitor = 2;
} else {
num_monitor--;
}
$('.frame_mon').css('display', 'none');
document.getElementById(arr_monitores[num_monitor]).style.display = "";
progresso = 0;
myStopFunction();
inicia();
};
function inicia() {
clearInterval(setintervalatualizaframe);
myStopFunction();
myVar = setInterval(function () {
if (progresso === 100) {
progresso = 0;
if (num_monitor === 2) {
location.reload();
//num_monitor = 0;
} else {
num_monitor++;
}
$('.frame_mon').css('display', 'none')
document.getElementById(arr_monitores[num_monitor]).style.display = "";
};
progresso++;
progresso++;
$('#example1').data('percent', progresso);
$('#example1').progress();
}, 3800);
}
function myStopFunction() {
clearInterval(myVar);
//atualiza_frame();
}
inicia();
function para_aplicacao(){
clearInterval(myVar);
atualiza_frame();
}
function atualiza_frame() {
clearInterval(setintervalatualizaframe);
setintervalatualizaframe = setInterval(function () {
document.getElementById(arr_monitores[num_monitor]).src=document.getElementById(arr_monitores[num_monitor]).src;
},1);
}
</script>
</html>
The way you are using setInterval and setTimeout is not properly
handled, as it creates a timer id to schedule execution. 0
A much more efficient way is to use the Promises async library, which is displayed below. 1
For websites that won't work, they are using a response header that won't allow their pages to be framed. You can work around this with some back-end program, where the server loads the web files then forwards them. 2
<!DOCTYPE html>
<html>
<head>
<title> Hello </title>
<style>
iframe {
display: block;
width: 1000px;
height: 500px;
margin-left: auto;
margin-right: auto;
}
iframe:focus {
outline: none;
}
button {
display: block;
margin: auto auto;
}
label {
display: block;
margin-left: auto;
margin-right: auto;
}
input {
display: block;
margin: auto auto;
}
</style>
</head>
<body>
<div id='main'>
<button id='wait' onclick='wait()'>Wait</button>
<label>Seconds</label>
<input type='number' id='seconds' placeholder='milliseconds'>
<button id='switching' onclick='webSwitch()'>Switch sites</button>
<iframe id='switchMe' src='https://codepen.io'></iframe>
</div>
<script>
//Array of webpages
var webList = ["https://www.bing.com", "https://www.walmart.com","https://www.codepen.io"];
//For tracking position in array
var count = 0;
//Function to be ran by event
function webSwitch() {
console.log('I have been called');
if (count >= webList.length) {
count = 0;
}
//Setting new URL
document.getElementById('switchMe').src = webList[count];
//Make sure to use next URL
count++;
}
function wait() {
console.log('Click!');
var numMS = document.getElementById('seconds').value;
sleep(numMS).then(() => {
webSwitch();
})
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
</script>
</body>
</html>

Remove <div> elements created by Javascript by using javascript

My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});

How to write html with javascript and display it on a slider?

I have created a basic slider that runs through images every 5 seconds while using javascript. My slider works just fine, but I'm not wanting to use it as an image slider anymore. I'm wanting to create a div with some more html design features and post that within my slider instead of my images. Going by this code below, what would I have to change and add to make it work?
<!doctype html>
<html>
<head>
<title>Ad Slider</title>
<style>
#slider
{
width: 800px;
height: 200px;
}
#sliderImages
{
width: 100%;
height: 100%;
border: 1px solid #06c;
border-radius: 10px;
}
</style>
<script type = "text/javascript">
var image1 = new Image();
image1.src = "sky.jpg";
var image2 = new Image();
image2.src = "chatImage.jpg";
var image3 = new Image();
image3.src = "orange.jpg";
</script>
</head>
<body>
<div id = "slider">
<img id = "sliderImages" src = "sky.jpg" name = "slide" />
<script type = "text/javascript">
var sliderAd = 1
function slideAds()
{
if (!document.images)
{
return;
}
document.images.slide.src = eval("image"+sliderAd+".src")
if (sliderAd < 3)
{
sliderAd++;
}
else
{
sliderAd = 1;
}
setTimeout("slideAds()",5000)
}
slideAds()
</script>
</div>
</body>
</html>
Now instead of adding those images, how can I add this type of content but working the same way like the images were?
<div>
<p>Some Content</p>
</div>
There are plenty of ways to write what you're looking for. Here's an augmented version of your code... You can toss whatever HTML you want into the innerHTML.
In the future, you're better of using Google to read up on the basics of Javascript...
<div id = "container">
</div>
<script type = "text/javascript">
MAXSLIDES = 2
slideText = 1
function slideAds() {
container = document.getElementById("container")
if(slideText == 1) {
container.innerHTML = "test1"
} else if (slideText == 2) {
container.innerHTML = "test2"
}
slideText += 1
if(slideText > MAXSLIDES) { slideText = 1 }
setTimeout("slideAds()",5000);
}
slideAds()
</script>
One of the easiest way is just to create an array of html you need, and than iterate through it inserting in each string as html in your holder div: here is an example from your question the only thing I used jQuery it is much easier that way.
<!doctype html>
<html>
<head>
<title>Ad Slider</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style>
#slider
{
width: 800px;
height: 200px;
}
#sliderImages
{
width: 100%;
height: 100%;
border: 1px solid #06c;
border-radius: 10px;
}
</style>
<script type = "text/javascript">
var arrayOfDiv = new Array();
arrayOfDiv[0] = "<div style='background-color:#FF0'>this is first div!</div>";
arrayOfDiv[1] = "<div style='background-color:#0ff'>this is second div!</div>";
arrayOfDiv[2] = "<div style='background-color:#f0f'>this is third div!</div>";
var sliderAd = 0;
function slideAds()
{
$("#sliderImages").html(arrayOfDiv[sliderAd]);
if (sliderAd < arrayOfDiv.length-1)
{
sliderAd++;
}
else
{
sliderAd = 0;
}
setTimeout("slideAds()",5000);
}
$(function(){
slideAds();
});
</script>
</head>
<body>
<div id = "slider">
<div id = "sliderImages" ></div>
</div>
</body>
</html>

Categories