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 years ago.
Improve this question
I am trying to give a javascript element a background image. This url is stored in a database and is not a string but a file path: https://firebasestorage.googleapis.com/v0/b/fir-firebase-182ca.appspot.com/o/images%2FScreenshot%20(2).png?alt=media&token=0edf4c43-e791-48b1-b2f4-b8ec5e65e296
I am also making a java script element, which is a div, to set its background image to this link:
var icon = document.createElement('img');
icon.style.cssText = "background-color: red;"
//icon.src = "'" + url + "'";
var parent = document.getElementById("loggedDisplay");
parent.appendChild(icon);
I havent been able to get this to work so far. How would I make this background image = the url
Try this,
document.getElementById("Your div ID").style.backgroundImage = "url('https://firebasestorage.googleapis.com/v0/b/fir-firebase-182ca.appspot.com/o/images%2FScreenshot%20(2).png?alt=media&token=0edf4c43-e791-48b1-b2f4-b8ec5e65e296')";
You can use style object directly too. But for css background you need to put the image url in a "url('')"
function myFunction() {
var imagePath = "https://firebasestorage.googleapis.com/v0/b/fir-firebase-182ca.appspot.com/o/images%2FScreenshot%20(2).png?alt=media&token=0edf4c43-e791-48b1-b2f4-b8ec5e65e296";
var icon = document.createElement('img');
icon.style.backgroundColor = "red";
//icon.src = imagePath ;
icon.style.backgroundImage = "url('" + imagePath + "')";
var parent = document.getElementById("loggedDisplay");
parent.appendChild(icon);
}
#loggedDisplay img {
display: block;
width: 100%;
height: 300px;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<div id="loggedDisplay"></div>
</body>
</html>
Related
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 4 years ago.
Improve this question
I am creating an api of images which looks like the following:
{
"images": [
{ "src": "http://placehold.it/100x100" },
{ "src": "http://placehold.it/100x100" },
{ "src": "http://placehold.it/100x100" }
]
}
I have integrated slick slider (http://kenwheeler.github.io/slick/) and the following code to append the images to the slider.
const jsonUrl = "./images.json";
$.getJSON(jsonUrl, function (json) {
var imgList = "";
$.each(json.images, function () {
imgList += '<div class="slide"><img src= "' + this.src + '"></div>';
});
$('.videos-slides .slide').append(imgList);
});
The HTML markup is as follows:
<div class="videos-slider">
<div class="videos-slides"></div>
</div>
I understand the logic of how this works but I need a push in the right direction to achieve this - The problem I'm getting is that the images are loading underneath each other. Partly because when I append the images to .video-slides .slide, it doesn't add the extra classes that are added by slick slider when you add a into the html itself.
I've initialised slick slider before all of the code above FYI.
Using the dedicated method slickAdd, the issue has been resolved.
const jsonUrl = "./images.json";
$.getJSON(jsonUrl, function (json) {
var imgList = "";
$.each(json.images, function () {
imgList += '<div><img src= "' + this.src + '"></div>';
});
$('.sy-videos-slides').slick('slickAdd', imgList);
});
You will need to refresh your slider after appending HTML
when you do
$('.videos-slides .slide').append(imgList);
do this too
$('.mySlider')[0].slick.refresh(); //replace .mySlider with actual DOM element
see demo - https://jsfiddle.net/5ox31m2a/2993/
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 6 years ago.
Improve this question
I made a little app and my button shows only on one place. It's all working but on wrong place. See pictures. I'll leave my GitHub repo link. Sorry most of stuff is on Cyrillic but code is, of course, on English Latin.
Here is a video of my problem (22 sec)
Thank you for your help.
You're problem is with id. HTML ids are unique, so when you do document.getElementById('skocko'), you only get back the first element with that id.
Instead, give the button a class of skocko, and access it like this:
Template.myTemplate.events({
"click .glasaj":function(event, template){
template.$(".skocko").toggle();
}
}
This will select the element with class skocko in the current template.
SRC: https://stackoverflow.com/a/27116956/2317712
check div positioning How to position one element relative to another with jQuery? so its position can be relative to button clicked, or assign unique skocko id for every skocko..
Do something like this in your script glasaj.js
if (Meteor.isClient) {
Template.glasajDugme.events({
'click .glasaj': function(){
var g = Meteor.user().profile.неискоришћениГласови;
if (g < 1) {
var pos = $(this).position();
// .outerWidth() takes into account border and padding.
var width = $(this).outerWidth();
//show the menu directly over the placeholder
$("#skocko").css({
position: "absolute",
top: pos.top + "px",
left: (pos.left + width) + "px"
}).show();
document.getElementById('skocko').style.display = "inline-flex";
// return "disabled" ;
}
else {
Predlozi.update(this._id, {$inc: {Број_Гласова: 1}}
);
Meteor.users.update(Meteor.userId(), {$inc: {"profile.неискоришћениГласови": -1}}
);
};
}
});
sakrijskocka = function(){
document.getElementById('skocko').style.display = "none";
};
};
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I'm using the function below to rotate images on click into the #home-image div, beginning with the first image.
Javascript:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
}
});
HTML:
<img id="home-image" src="img1_on.jpg" />
But
I want to "echo" the file name of the image being displayed, so the viewer sees the name of the image.
How would I "echo" the name of the image into another div, i.e. <div id="home-image-name"></div>?
This is an attempt to echo the output of src into the home-image-name div, but it doesn't work:
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("#home-image-name").innerHTML = output;
}
});
This works, with the additional window.onload functions to show the image name on page load:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
$('#home-image').on({
'click': function () {
var origsrc = $(this).attr('src');
var src = '';
if (origsrc == 'img1_on.jpg') src = 'img2_on.jpg';
if (origsrc == 'img2_on.jpg') src = 'img3_on.jpg';
if (origsrc == 'img3_on.jpg') src = 'img4_on.jpg';
if (origsrc == 'img4_on.jpg') src = 'img1_on.jpg';
$(this).attr('src', src);
var output = 'src';
document.getElementById("home-image-name").innerHTML = src;
}
});
}
So, from what I said + #j08691 comment, the correct sintax would be:
document.getElementById("home-image-name").innerHTML = src;
As the getElementById method takes a string of the id, with no need of #. And output was just a string, so you could either change output = src which is kind of redundant, or just put src.
Jquery way:
$("#home-image-name").html(src)
If you want to also do it on page load before click:
window.onload = function(){
$("#home-image-name").html($('#home-image').attr("src"))
}
Using jQuery, a simple:
$('#home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
should work.
jsFiddle example
Also if you wanted to use this code with several images, you could use the following (which uses a common class):
$('.home-image').click(function(){
$('#home-image-name').html(this.src.split('/').pop())
})
jsFiddle example
remove the # from
document.getElementById("#home-image-name").innerHTML = output;
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 7 years ago.
Improve this question
I'm using a for loop to dynamically name and fill buttons (with text and with code). One thing I had a problem with was dynamically allocating onclick functionality to the buttons, but I seemed to have fixed it with:
document.getElementById(ID_HERE).onclick = FUNCTION();
The problem is when I add this code, the buttons trigger themselves on the load of the webpage instead of the click.
I put the full code below for both the HTML and the Javascript.
JavaScript:
var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
document.write("<div id='container'>");
document.write("<center><b> Welcome to ");
document.write(currentRoute);
document.write("!<br>")
document.write("Your options are:");
for (i = 0; i<routes.length;i++){
var options = routes[i];
var temp = "button" + i
document.write("<button id='button'></button>");
document.getElementById('button').id = temp;
document.getElementById(temp).innerHTML=routes[i][0];
document.getElementById(temp).onclick = getRoutes(routes[i][1]);
console.log(routes[i]);
console.log(routes[i][1]);
}
document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
document.write("</b></center></div>");
}
function getRoutes(locationid) {
var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
$.ajax({
type: 'GET',
url: routesURL
}).done(function(data) {
console.dir(data);
dataParsed = JSON.parse(data);
currentRoute = dataParsed.prefname;
routes = dataParsed.routes;
console.log(routes);
clearScreen();
});
}
function clearScreen(){
if (document.contains(document.getElementById("container"))){
elem = document.getElementById("container");
elem.remove();
}
possibleRoutes();
}
HTML:
<html>
<head>
<title> Londinium Trail </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://192.168.1.151:8000/scripts/game.js"> </script>
</head>
<body>
<script>
getRoutes(50017);
</script>
</body>
</html>
JAVASCRIPT
Try to use addEventListener instead :
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
If you're using jquery :
$('body').on('click', '#ID_HERE', myFunction);
Take a look at addEventListener vs onclick.
Hope this helps.
The issue is that you are calling the function by using FUNCTION();
Since your code appears to be using JQuery, consider using the .on method to attach a click listening:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});
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
I have an image in HTML, and I wish when the mouse enter in image, this image change quickly, with an infinite loop. I have a lot of image to display (logo_white, logo_red, logo_blue, logo_green, ...)
HTML
<img src="img/logo_white.png" alt="Logo" id="logo" />
JS
$('#logo').mouseenter(function() {
var src = ($(this).attr('src') === 'img/logo_white.png')
? 'img/logo_red.png'
: 'img/logo_white.png';
$(this).attr('src', src);
});
This JS code "work". But I think it could be better.
Thanks you in advance for your response.
Not a 100% sure what you mean, but maybe an example like this is what you are looking for or can get you started.
This example:
Create an array with the links to your images
Preload these images
For the 'mouseenter' event start an interval and switch the logo to the next one in the array (Or continue where it left off)
For the 'mouseleave' event, stop the interval.
Initializes the first image when the page is fully loaded including graphics. https://api.jquery.com/load-event/
You can change the variable intervalInMilliseconds to speed it up or slow it down.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var interval;
var currentImageNumber = 0;
var intervalInMilliseconds = 1000;
var images = [
"img/logo_green.png",
"img/logo_blue.png",
"img/logo_red.png",
"img/logo_white.png"
];
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
function switchLogo(imageNumber) {
$('#logo').attr('src', images[imageNumber]);
currentImageNumber = currentImageNumber === images.length -1 ? 0 : ++currentImageNumber;
}
preload(images);
$(document).ready(function() {
var logo = $('#logo');
logo.mouseenter(function() {
interval = window.setInterval(function () {
switchLogo(currentImageNumber)
}, intervalInMilliseconds);
});
logo.mouseleave(function() {
clearInterval(interval);
});
});
// When all the images are loaded
$(window).load(function() {
// Initialize this to the first image
switchLogo(currentImageNumber);
});
</script>
</head>
<body>
<img src="" alt="Logo" id="logo" />
</body>
</html>