I'm trying to change the background of the body on my HTML doc using some basic JS functions. I have set the function to target a specific ID, and then the style.background tag, if it is the current background image, then set it to another one I specified, else keep the same image. I have tried changing the code countless times now, but still can't seem to get it to change the background. Any help with this would be appreciated.
HTML:
<div class="bg-image"
style="background-image: url('./img/frankie.jpg');
height: 100vh" id="bacgr"> <!--SETS BACKGROUND using id tag to change w/ JS-->
<main role="main" class="container d-flex justify-content-center">
<div class="starter-template">
<h1>Bootstrap starter template</h1>
<p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
</div>
</main>
</div>
JS:
let myImage = document.getElementById('bacgr').style.backgroundImage; //have to target specific image(like an array ([0])), put inside div w/ id.
myImage.onclick = function() {
if(myImage === "url('./img/frankie.jpg')") {
myImage == "url('./img/jesus_mobile.jpg')";
} else {
myImage == "url('./img/frankie.jpg')";
}
}
Try this:
const el = document.getElementById('bacgr');
el.onclick = function() {
if(this.style.backgroundImage === "url('./img/frankie.jpg')") {
this.style.backgroundImage = "url('./img/jesus_mobile.jpg')";
} else {
this.style.backgroundImage = "url('./img/frankie.jpg')";
}
}
Here is the example
You are changing only the URL, but that will not be assigned back to the dom element.
const el = document.getElementById('bacgr');
let prev = 'url("https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa")';
el.onclick = function() {
el.style.backgroundImage = prev === el.style.backgroundImage ? 'url("https://images.unsplash.com/photo-1583508915901-b5f84c1dcde1")' : prev;
}
<div class="bg-image" style="background-image: url('https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa');
height: 100vh" id="bacgr">
<main role="main" class="container d-flex justify-content-center">
<div class="starter-template">
<h1>Bootstrap starter template</h1>
<p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
</div>
</main>
</div>
Related
What is the javascript in order to only display posts 3 & 4 in order???
Also I need it be dynamic so if I put a 5th post it will only display 4th and 5th posts... I was thinking about something like a date function or a simple incrementor but can't seem to figure it out. I'm new to javascript and have been trying different things but no avail... Thanks in advance...
<!DOCTYPE html>
<html>
<body>
<div id="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div id="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div id="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div id="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You dont need script for that. You can do it with CSS.. I have changed your html little bit (made posts-div class in html).
.posts-div{
display:none;
}
.posts-div:nth-child(-n+2) {
display:block;
}
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post5</h1>
<p class="post">post5</p>
</div>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
<script>
// ???
</script>
</body>
</html>
You can test it on JSfiddle as well.. https://jsfiddle.net/nimittshah/b5eL3ykx/6/
$('.posts-div:gt(1)').hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</body>
Try this:
<script>
document.addEventListener("DOMContentLoaded", function () {
var allPosts = document.querySelectorAll(".posts-div");
// This is the number of posts you want displayed
var numberOfPostsToShow = 2;
for (var i = 0; i < allPosts.length; i++) {
if(i > numberOfPostsToShow - 1) {
allPosts[i].style.display = "none";
}
}
});
</script>
This way you will choose how many posts you want to be shown with the numberOfPostsToShow variable.
Let me know if this worked. Regards.
The way I interpreted your question, you need a way to:
show only the first n elements;
add new elements to the top of the list of posts, dynamically;
when you add them, update the visible elements.
Assuming a slightly modified version of your code, which corrects the id/class issue and adds a container for all the posts (this time with a proper id):
<!DOCTYPE html>
<html>
<body>
<div id="posts-container">
<div class="posts-div">
<h1 class="post-title">post4</h1>
<p class="post">post4</p>
</div>
<div class="posts-div">
<h1 class="post-title">post3</h1>
<p class="post">post3</p>
</div>
<div class="posts-div">
<h1 class="post-title">post2</h1>
<p class="post">post2</p>
</div>
<div class="posts-div">
<h1 class="post-title">post1</h1>
<p class="post">post1</p>
</div>
</div>
<script>
// ???
</script>
</body>
</html>
this code will do the trick and manage both the addition and the updates to the visibility of the posts:
function showOnly(visible, query){
var elements = document.querySelectorAll(query);
for (var i = 0; i < elements.length; i++){
if (i < visible - 1){
elements[i].style.display = 'block';
} else {
elements[i].style.display = 'none';
}
}
}
function publishPost(element, visible){
showOnly(visible, '#posts-container .posts-div')
var elements = document.querySelectorAll('#posts-container .posts-div');
element.style.display = 'block';
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}
}
The showOnly function (to be called with the number of elements to be shown and the string that identifies the elements with querySelectorAll) will only make visible the first n elements identified by the string. You can use it independently of the rest of the code if needed.
The publishPost function, on the other hand, is strictly dependent on the modified html above (to use it elsewhere you will need to adjust the strings fed to querySelector and querySelectorAll). It takes the element to be published as the first argument, the number of elements that need to be visible as the second. Then it updates the list of posts prepending the new one to it, and it also updates which posts are visible.
This is a code sample that uses it:
var elDiv = document.createElement('div');
var elH1 = document.createElement('h1');
var elP = document.createElement('p');
elDiv.classList = 'posts-div';
elH1.classList = 'post-title';
elP.classList = 'post';
elH1.innerText = 'some title';
elP.innerText = 'some text for the post';
elDiv.appendChild(elH1).appendChild(elP);
publishPost(elDiv, 2);
showOnly
This function starts by getting a list of the elements whose visibility must be managed:
var elements = document.querySelectorAll(query);
then it loops through the list and examines each element:
for (var i = 0; i < elements.length; i++){
if it has to be visible, it sets the style.display property to 'block':
if (i < visible){
elements[i].style.display = 'block';
otherwise it sets it to 'hidden':
else {
elements[i].style.display = 'none';
publishPost
This function starts by showing only n-1 elements (because it will need to add a new, visible element to the top of the list):
showOnly(visible - 1, '#posts-container .posts-div')
then it retrieve the current posts:
var elements = document.querySelector('#posts-container .posts-div');
it makes the new element visible:
element.style.display = 'block';
finally, it adds the element to the top of the list (the different syntax depends on wether the list is empty):
if (elements.length > 0) {
document.querySelector('#posts-container').insertBefore(element, elements[0]);
} else {
document.querySelector('#posts-container').appendChild(element);
}
I have this code that is generated by php:
<div class="fusion-post-content post-content">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
<div class="fusion-post-content-container"></div>
</div>
I need to wrap two elements by using javascript so the code would look like this:
<div class="fusion-post-content post-content">
<div class="class">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
</div>
<div class="fusion-post-content-container"></div>
</div>
This will do what you want. Isn't it better to change the code on server-side??
// Select the first element found
var parent = document.querySelector('.fusion-post-content');
console.log('Old child-length', parent.children.length);
console.log('Old:', parent.innerHTML);
// *You don't need the timeout
setTimeout(function () {
var h2 = parent.firstElementChild;
var p = parent.firstElementChild.nextElementSibling;
// Remove cildren
parent.removeChild(h2);
parent.removeChild(p);
// Insert the new child
parent.insertAdjacentHTML('afterbegin', '<div class="class"></div>');
// Insert the other children (old) in the new child
parent.firstElementChild.insertAdjacentElement('beforeend', h2);
parent.firstElementChild.insertAdjacentElement('beforeend', p);
// Gets one less, since we put to children in one (3 - 1 = 2)
console.log('New child-length', parent.children.length);
console.log('New:', parent.innerHTML);
}, 500);
<div class="fusion-post-content post-content">
<h2 class="blog-shortcode-post-title"></h2>
<p class="fusion-single-line-meta"></p>
<div class="fusion-post-content-container"></div>
</div>
I am trying to make an image change when I click on a piece of text on a website that I am building.
At this moment I have created a class called device with one of them being device active as shown below:
<div class="col-md-3">
<div class="device active">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
</div>
And then what i am currently trying to do is remove the class of active when I click on some text with the i.d of #search2. This is my whole jquery script so far:
$("#search2").click(function() {
var currentImage = $('.device.active');
var nextImage = currentImage.next();
currentImage.removeClass('active');
});
However this does not seem to remove the class of active and the image is still displayed? any ideas?
Your selection is done right and it is working for me (the active class is removed from that item). The problem must be somewhere else in your code.
Here is an alternative:
var activeDeviceIndex = 0;
$("#search2").click(function() {
var devicesContainer = $('.device');
$(devicesContainer[activeDeviceIndex]).removeClass('active');
activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
$(devicesContainer[activeDeviceIndex]).addClass('active');
});
.device {
display: none;
}
.device.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="device active">
<p>Device 1</p>
</div>
<div class="device">
<p>Device 2</p>
</div>
<div class="device">
<p>Device 3</p>
</div>
</div>
<button id="search2">click</button>
Check on the following, the id on the button to click should be search2 and not #search2, may be just typo stuffs.
after that update your code as follows
/**
*#description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*#param {Element} current - the currently active image
*#param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
var next = islooped? current : current.nextSibling;
while(next && next.nodeName.toLowerCase() !== 'div') {
next = next.nextSibling;
}
next = next? next : nextImage(current.parentNode.firstChild, true);
return next;
};
$('#search2').bind('click', function(event) {
var current = $('.device.active').removeClass('active').get(0);
var next = nextImage(current, false);
$(next).addClass('active');
});
I have 2 images displayed on a page. I want a message to appear when I click 1 image and it to disappear when I click the alternate one, then vice versa.
The jQuery code I created below seems to be working fine, but I am continuously getting an [object HTMLImageElement] message on the alternate image every time I click the one that is displaying the text.
$(document).ready(function(){
$("#gimp").click(function(){
var gimp = "Gimp message.";
var i = $("#qInkscape").text(inkscape);
if (i == true) {
$("#qInkscape").hide();
$("#qGimp").text(gimp);
} else {
$("#qGimp").text(gimp);
}
});
$("#inkscape").click(function(){
var inkscape = "Inkscape message";
var g = $("#qGimp").text(gimp);
if (g == true) {
$("#qGimp").hide();
$("#qInkscape").text(inkscape);
} else {
$("#qInkscape").text(inkscape);
}
});
});
And the html
<div class="mf-container">
<div class="mf-content">
<div class="row">
<div class="mf-third mf-center">
<img src="img/qualifications/gimp_g.png" class="mf-pic-unique mf-pic-
shadow mf-margin-top" id="gimp" alt="about gimp">
<p id="qGimp" class="mf-off-black-text"> </p>
</div>
<div class="mf-third mf-margin-top">
<p class="mf-center mf-off-black-text">Click on an image to learn more
about each technology</p>
</div>
<div class="mf-third mf-center">
<img src="img/qualifications/inkscape_G.png" class="mf-pic-unique mf-
pic-shadow mf-margin-top" id="inkscape" alt="about inkscape">
<p id="qInkscape" class="mf-off-black-text"> </p>
</div>
</div>
</div>
</div>
There is requirement where I need to copy HTML code on click of button. The functionality is not working where we are using a video tag. The video tag somehow gets formatted by brightcove. I tried using <pre> and <code> elements. Can you please suggest something.
$('.copy').on('click', function() {
var section = $(this).next().find('code').html();
var elem = document.createElement('textarea');
//elem.textContent = section;
elem.innerHTML = section;
//elem.classList.add('invisible');
document.body.appendChild(elem);
console.log(elem.innerHTML);
elem.select();
console.log("Hi");
try {
document.execCommand('copy');
} catch (e) {
console.log('ERROR: ' + e);
} finally {
elem.remove();
}
});
<div class="ply-item-ratio-content">
<!-- Start of Brightcove Player -->
<div class="parbase brightcovevideo section">
<div style="margin-bottom: 0;margin-left: 0;margin-right: auto;margin-top: 0;overflow-x: hidden;overflow-y: hidden;text-align: center;width: 1025px;text-align:left; height: 560px;">
<div id="25efba484"> </div>
<script type="text/javascript" src="/etc/polycom/www/global/js/thirdparty/BrightcoveExperiences_embedded.js"></script>
<script>
customBC.createVideo("1000", "567", "4223245001", "cd~~,AddB-EKwxDE~,eUqCcdvdv7u6CqAyJC", "4435446654001", "2768ede1a35dsgfdgffba484");
</script>
</div>
</div>-->
<!-- End of Brightcove Player -->
</div>
</div>
<div class="ply-global-video-description">
<h2>NATO Communications and Information (NCI) Agency Success Story</h2>
<p>Centro to create a relaxed working environment that draws teams closer together and enables better sharing of ideas and insights.</p>
</div>
</div>