I'm new to coding and am trying to enlarge an image onclick and then un-enlarge an image onclick, using JavaScript. I've tried using jQuery but jQuery doesn't seem to work so I'm simply using JavaScript.
This is the JavaScript:
var myImg1 = document.getElementById('myImg1')
var myImg2 = document.getElementById('myImg2')
var myImg3 = document.getElementById('myImg3')
myImg1.onclick = function() {
if (myImg1.style.height = '100px') {
myImg1.style.height = '1000px'
return
} else {
myImg1.style.height = '100px'
return
}
}
The image has the class assigned 'i' in HTML and CSS, which sets the width as 100px.
The code does successfully enlarge the image to 1000px but it doesn't un-enlarge.
I've tried quite a few different methods, but mostly with jQuery and I can't get jQuery to work.
you need to use 2 equal signs to compare two things, one equal sign means you are trying to set a value for that variable.
if (myImg1.style.height == '100px') {
myImg1.style.height = '1000px'
// return
}
as Pato Salazar mentioned in the comments the return statement isn't needed.
JavaScript:
var myImg1 = document.getElementById('Img1');
myImg1.onclick = function() {
if (myImg1.style.height == '1000px') {
myImg1.style.height = '100px';
} else {
myImg1.style.height = '1000px';
}
}
OR
jQuery:
jQuery(document).ready(function() {
jQuery('#Img1').click(function() {
jQuery('#Img1').toggleClass('img1_1000px');
});
});
Both work. If you need jQuery, use to write < img src="Img1.jpg" id="Img1" style="height: 100px;" > and .img1_1000px { height: 1000px!important; } in style.
I hope I helped you.
Related
I want to change the font size to 36px if my h1 has more than two words and keep it as is if not.
This is my code:
window.addEvent('domready',function() {
var $quote = ('#header .col-sm-12 h1');
var $numWords = $quote.get('text').split(' ').length;
if (2 < $numWords) {
$quote.setStyle('font-size','36px'); }
});
However, it doesn't work. What's wrong with it?
The site in question is 6wo.de
Please note: Changing the size via CSS by using the viewport unit is not an option in this case.
First of all it's not addEvent but addEventListener. Then you probably mean DOMContentLoaded, because domready is not an event.
To make the title smaller give an id or class to identify it easier in JavaScript.
<h1 id="page-title">My page title</h1>
Now you can make the title smaller like this.
window.addEventListener('DOMContentLoaded', function() {
const title = $('#page-title');
var numWords = title.text().split(' ').length;
if (numWords > 2) {
title.css('font-size', '36px');
}
});
UPDATE
If you don't want to give an id to the title for some reason, you can do like this.
window.addEventListener('DOMContentLoaded', function() {
const title = $('#header .bottom-header h1');
var numWords = title.text().split(' ').length;
if (numWords > 2) {
title.css('font-size', '36px');
}
});
I am trying to make multiple images (3) fade in and out as parallax background. I am currently using a large animated gif which is not going to cut it due to the loading times and what I eventually need. I am trying to target a "data-background" attribute which I have done but can't seem to get the images to change. I can get it to output in the console but not the data-background. Below is the code.
Thanks!
<section id="paralax-image" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1"
data-gradient="1">
(function () {
// The images array.
var images = ["assets2/Arcadian.jpg", "assets2/AngryPrawns.jpg", "assets2/Apricot_Smash.jpg"];
// The counter function using a closure.
var add = (function() {
// Setting the counter to the last image so it will start with the first image in the array.
var counter = images.length - 1;
return function() {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter+=1;
}
return counter;
}
})();
// The function for changing the images.
setInterval(
function() {
var section = document.getElementById("paralax-image");
section.getAttribute("data-background");
section.setAttribute('data-background', images[add()]);
console.log(images[add()]);
}
, 3000);
})();
First of all, attributes that have "data-" in front of them are only used to store some custom data on elements. Those attributes do not influence the appearance/behaviour of your app in any way unless you use them in your JS/CSS.
So, in your code, you are setting the data-background attribute on your section. The code is working correctly and if you look into the inspector, you can actually see that that attribute's value is changing as expected.
The next step for you would be to display the images that you set in your data-background attribute - either using JS or CSS.
Unfortunately, for now, it's not possible to grab the background URL from attribute value in CSS as described in the top-voted answer here: Using HTML data-attribute to set CSS background-image url
However, you can still manually set the CSS background-image property using JavaScript based on the "data-" property.
// The images array.
const images = ["https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&h=350", "https://images.unsplash.com/photo-1530482817083-29ae4b92ff15?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=44f4aebbd1e1371d5bf7dc22016c5d29&w=1000&q=80"];
const imagesSwitcher = () => {
const getCounter = () => {
// Setting the counter to the last image so it will start with the first image in the array.
let counter = images.length - 1;
return () => {
// When the last image is shown reset the counter else increment the counter.
if(counter === images.length - 1) {
counter = 0;
} else {
counter += 1;
}
return counter;
}
}
const counter = getCounter();
const updateBackground = () => {
const section = document.getElementById("paralax-image");
section.style.background = `url(${images[counter()]}) no-repeat`;
};
updateBackground();
setInterval(() => updateBackground(), 3000);
};
imagesSwitcher();
.dynamic-background {
display: block;
width: 500px;
height: 200px;
background-size: 100%;
}
<div>
<section id="paralax-image" class="dynamic-background" style="height: 400px;" class="module-cover parallax" data-background="" data-overlay="1" data-gradient="1">
</section>
</div>
The thing is - in this case, you don't even actually need this data-background property. You can simply switch background image using JS.
Now, it's not very clear what you meant by parallax in your case. In case you actually meant parallax background like in here http://jsfiddle.net/Birdlaw/ny8rqzu5/, you would need to take a different approach overall. Please comment if you need any help with this.
I've made a slider with jQuery using html tags which have classes instead of IDs so that I will be able to use the same jQuery code for other duplicated sliders.
The problem is, I want the width of my ul to be calculated based on the number of lis, instead of setting it manually in CSS. When there is only one slider I can set my vars outside of the function, but when I have to use it though event attributes on my html parts so that I will be able to use them for multiple sliders, I have to move the vars inside of my function, which sets the wrong width.
This is my code:
function OLAR(direction,span) {
var OurNexNPrv = $(span);
var Parent_OLAR = OurNexNPrv.parents('.OLAR');
var UL_OF_OLAR = Parent_OLAR.find('.OLAR_CONTENT ul');
var LI_OF_OLAR = UL_OF_OLAR.find('li');
var LI_OF_OLAR_LENGTH = LI_OF_OLAR.length;
var Quantity_OF_OLAR_PAGES = LI_OF_OLAR_LENGTH / 3;
var Max_Margin_LEFT = -(Quantity_OF_OLAR_PAGES - 1) * 576;
UL_OF_OLAR.css('width',LI_OF_OLAR_LENGTH*192);
var AffectedLeftMargin;
var CurrentLeftMargin = UL_OF_OLAR.css('margin-left');
CurrentLeftMargin = parseFloat(CurrentLeftMargin);
if (direction == 'right') {
AffectedLeftMargin = CurrentLeftMargin - 576;
}
if (direction == 'left') {
AffectedLeftMargin = CurrentLeftMargin + 576;
}
if (AffectedLeftMargin < Max_Margin_LEFT) {
AffectedLeftMargin = 0;
}
if (AffectedLeftMargin > 0) {
AffectedLeftMargin = Max_Margin_LEFT;
}
UL_OF_OLAR.animate({'marginLeft': AffectedLeftMargin}, 1000);
}
$('.CIRCLE_LOAD_RIGHT').click(function () {
OLAR('right');
});
$('.CIRCLE_LOAD_LEFT').click(function () {
OLAR('left');
});
How can I set the width for each of my uls individually, through css commands outside of that function?
Okay, my ul tag did not have the absolute position; after giving it the right position and left:0 and bottom:0 or right:0 and bottom:0 (based on your language)the given width which comes from JQuery code can rhyme perfectly with everything else. I've tried it with multiple sliders and it works perfectly :)
So, we need an anchor point in order to make this work. And there is nothing wrong with this JQuery code which has been mentioned above!
Have a great day.
Hello I want to make a Menu thats pops out of the side when I click a button. I have it all set up with the CSS but the Javascript part doesn't work.
I want to test if the width of menubarWrapper is equal to 300 then the width of the menubarWrapper needs to change to 0px and if it isn't equal to 300px than change it to 300px.
I have the following JS:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if menuWrapper.width == 300 {
menuWrapper.style.width = "0";
} else {
menuWrapper.style.width = "300";
}
}
I also tried in the IF statement menuWrapper.style.width but that doesn't work also
There are other answers that are just fine --
use "300px", not "300"
Surround your conditional with a parentheses.
(You'll need both, by the way.)
But I wanted to make sure that somewhere on this page, someone pointed out that this is a very brittle way of toggling. You have a magical, hardcoded integer for the size, which might break if you ever wanted to style things differently. And if you decide one day to fade out the menu, then the test won't work at all.
Might I suggest that, instead, you create two classes in CSS:
.menu-item { width: 300px; }
.menu-item.collapsed { width: 0; }
And then in javascript, you'll only have to write the following:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
menuWrapper.classList.toggle('collapsed');
}
Not only is the intention easier to read, but this will allow you to swap out the behavior if you decide that, instead of purely narrowing the menu, you might want it to fade out, or animate it to the left, or... well... whatever can come up with.
Your script has a typo. Add '()' for an if statement.
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if (menuWrapper.width == 300) {
menuWrapper.style.width = "0";
} else {
menuWrapper.style.width = "300";
}
}
When changing the width of an element via style.width, you have to append px to the end of the string:
function menuBarToggle() {
var menuWrapper = document.getElementById('menuWrapper');
if menuWrapper.width == 300 {
menuWrapper.style.width = "0px";
} else {
menuWrapper.style.width = "300px";
}
}
I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};