Add class if image has the class - javascript

I have some images which are way too big when I make the menu they're containing in smaller, that's why I made a second class where I changed the width and height.
I tried to add and remove the class with javascript like this:
if ($('img').hasClass('lorem')) {
$('img').removeClass('lorem')
$('img').addClass('smalllorem')
} else {
$('img').addClass('lorem')
$('img').removeClass('smalllorem')
}
Now this works perfectly fine, but this will add the classes to my other images on the website as well, how can I specify to only give the class "smalllorem" to the elements which have the class lorem? Because the other images don't have the class "lorem" they will still get the class "smalllorem" added on.
-> I don't get why images without the class "lorem" get into the code? I mean I ask if the image has class .. Why does it include the other image elements?

I would look for a CSS solution before moving on to a JavaScript one. But answering the question asked...
I don't get why images without the class "lorem" getting into the code ? I mean I ask if img has class
Because $("img") selects all images, but $("img").hasClass("lorem") only looks at the first image to see if it has the class. Then in each branch of your if/else, you're applying changes to all images ($("img").addClass("lorem");). jQuery's API is asymmetric in this regard: methods that tell you something about the element only look at the first element in the jQuery collection, but methods that change something apply to all elements in the collection.
If I understand you correctly, you want to:
Remove lorem from images that have it, adding smalllorem instead
and
Remove smalllorem from images that have it, adding lorem instead
Basically, you want to toggle both classes. There's a toggleClass method for that.
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
That selects all img elements that have either class, and toggles the classes on them.
Live Example:
setTimeout(() => {
$("img.lorem, img.smalllorem").toggleClass("lorem smalllorem");
}, 800);
.lorem {
border: 2px solid black;
}
.smalllorem {
border: 2px solid yellow;
}
<div>lorem (black border) => smalllorem (yellow border):</div>
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="lorem" src="https://via.placeholder.com/50.png/09f/fff">
<div>smalllorem (yellow border) => lorem (black border):</div>
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<img class="smalllorem" src="https://via.placeholder.com/50.png/09f/fff">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Instead of adding a new class to the image you could just make it responsive :
.img {
width: 100%; //define width
max-width: 250px; //restrict the size (can use min-width aswell)
height: auto; //auto adjust depending on the width
}
var count = 0;
function resize(){
var menue = document.getElementById("container");
count++;
if(count % 2)
{
menue.style.width = "50%";
menue.style.height = "50px";
}
else
{
menue.style.width = "100%";
menue.style.height = "100px";
}
}
#container{
border: 1px solid black;
width: 100%;
height: 100px;
transition: 330ms;
}
#home{
width: 15%;
height: auto;
min-width:10px;
}
menue
<div id="container">
<img src="https://cdn-icons-png.flaticon.com/512/25/25694.png" id="home">
</div>
<br>
<input type="button" value="resize menue" onclick="resize()">

Related

Toggling HTML visibility using CSS and jQuery

Ok so I have a div that contains a canvas and a span which contains an image. I want it such that if the user hovers over or focuses on the div that the image inside of the span will appear. The image wil be invisible otherwise.
Long story short I want to have a canvas with a red 'X' on the corner that is only visible when the canvas is active
$('image-canvas').hover(function() {
$('delete-image').addClass('active');
}, function() {
$('delete-image').removeClass('active');
})
.delete-image {
position: absolute;
top: 0px;
right: 0px;
}
.delete-image>img {
width: 32px;
visibility: hidden;
}
.delete-image.active>img {
width: 32px;
visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canvas-container" tabindex="1">
<canvas id="imageCanvas"></canvas>
<span class="delete-image">
<img src="file:///E:/Apps/Emoji-App/emojis/icons/if_erase_delete_remove_wipe_out_181387.png"/>
</span>
</div>
The hover event fires just fine but the image refuses to toggle visibility. Any help?
When you use a class within your selector, write it like this:
$('.myDiv')
When you use an ID within your selector, write it like this:
$('#myDiv')
For further informations, check out jQuery's learning center website.
Seems like you have misspelled or have not specified the jQuery selector type (class . or id #). Please try this:
$('#imageCanvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
See here .
$("#control").mouseover(function(){
$('#img').show();
});
$("#control").mouseout(function(){
$('#img').hide();
});
#img{
display:none;
}
#control{
margin-bottom:10px;
padding:5px;
background-color:#eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='control'>Show/Hide</div>
<img src='https://cdn.sstatic.net/Sites/stackoverflow/img/404.svg' id='img'>
The question is not well-phrased, so I ain't sure I totally understood what you wanted.
When you try to select by class, don't forget the dot '.'
$('image-canvas').hover(function () {
$('.delete-image').addClass('active');
}, function () {
$('.delete-image').removeClass('active');
})
When using functions 'addClass', 'removeClass', 'toggleClass', etc. - you don't use the '.' sign because it is a function that refers only to classes. On the other hand, when using jQuery selector $(' ') or vanilla querySelector(' '), you should declare what kind of attribute you are selecting by, those will be '#' for ID, '.' for Class, and if you want to select by anything else you can use $('*[anyattribute=anyvalue]'), in your clase it could be $('span[class=delete-image]').
Good luck

Dynamic mouseenter

I appended a few divs with inside img tags. Every tag has own unique id = "theImg"+i where "i" is number. I want to mouseover on specific img and show the content of span (which also have specific id with number). Here is my code so far but not working.
var j;
document.onmouseover = function(r) {
console.log(r.target.id);
j = r.target.id;
}
$(document).on({
mouseover: function(e){
$("span").show();
},
mouseleave: function(e){
$("span").hide();
}
}, "img#"+j);
If you have a span after every img, maybe it's a good idea to not use JavaScript at all? ;-)
You could use :hover pseudoclass in CSS, making your thing always work reliably.
Consider the following example:
img + span {
display: none;
}
img:hover + span {
display: block;
}
/*/ Optional styles /*/
div {
position: relative;
float: left;
}
div img + span {
position: absolute;
color: #fff;
background: #27ae60;
border: solid 1px #2ecc71;
border-radius: 50px;
z-index: 1;
bottom: 1em;
width: 80%;
left: 50%;
margin-left: -43%;
padding: 2% 3%;
text-align: center;
}
<div>
<img src="https://placehold.it/400x200">
<span>This is an image of a gray rectangle!</span>
</div>
<div>
<img src="https://placehold.it/200x200">
<span>This is an image of a gray square!</span>
</div>
<div>
<img src="https://placekitten.com/g/400/200">
<span>This is an image of a cute kitten inside a rectangle!</span>
</div>
<div>
<img src="https://placekitten.com/g/200/200">
<span>This is an image of even cuter kitten inside a square!</span>
</div>
So the issue is that you are trying to set your handler on a dynamic selector ("img#"+j) but this will not work. For one thing, that equation will be evaluated only once, on page load, when j is undefined.
So you want to do this instead:
target only img tags for your mouse over... Better yet, give your special images all the same css class so you can attach the event handlers only to those. That will be more efficient.
When an image is moused over or out of, grab it's id attribute, extract the number from it, then use that to build a selector for the appropriate span to show.
var get_span_from_image = function(image) {
var image_id = image.attr("id");
var matches = image_id.match(/theImg(\d+)/);
if(matches) return $("theSpan" + matches[1]);
return $(); // nothing found, return an empty jQuery selection
};
$("img").hover(
function() { // mouse over
get_span_from_image($(this)).show();
},
function() { // mouse out
get_span_from_image($(this)).hide();
}
);
Note: There are better ways to "link" two nodes together, but this is just to answer your question with the current structure you have.
UPDATE: Some ideas to link two nodes together
So instead of trying to extract a number from an id attribute, a better way would be to tell either one of the image or span about it's sibling. You could output your html like this, for instance:
<img id="theImg1" data-target="theSpan1" class="hoverable" src="..."/>
....
<span id="theSpan1">...</span>
Of course now your ideas could be anything - you don't have to use numbered values or anything.
Then your hover code becomes quite simply:
var get_span_from_image = function(image) {
var span_id = image.data("target");
return $("#" + span_id);
};
$("img").hover(
function() { // mouse over
get_span_from_image($(this)).show();
},
function() { // mouse out
get_span_from_image($(this)).hide();
}
);
Hope this helps!

Selecting child of previous parent jQuery

Lately I've been trying my hand at animation using CSS and jQuery, it went well, however, now I want to do a bit more.
That is, once the user clicks information should show up on top of the image.
At the moment, I just have a few tags on which I perform the animations and class toggles.
My question is, I've thought about doing the following:
<div class= "singleImage">
<img src.... class="actualImage">
<p>text to put over the image</p>
</div>
This would be done per image which means that I'll have about 5 of them with different images.
However, I don't know how to go about selecting the previous element of class "actualImage".
Has anyone got any suggestions?
Thank you
Use the jQuery prev function. Example: Assume you want to select the image previous to the second image:
var foo = $(".singleImage").eq(1);
var bar = $(foo).prev().find('.actualImage');
Fiddle
Try this:
$('singleImage').children('.actualImage').prev();
I'm not sure why you are trying to select the previous element, but you could do something akin to this:
Bind a function to the click event for the element containing your image and caption.
Inside this function, toggle the caption.
Also, bind a click event handler to the body to detect clicks "off" the containing element.
HTML:
<a href="#" class="has-caption">
<img src="http://placehold.it/300x300" />
<span class="caption">This is a caption</span>
</a>
CSS:
a.has-caption { position: relative; }
a.has-caption .caption {
background: rgba(0, 0, 0, .25);
bottom: 0;
color: #fff;
display: none;
height: 20px;
left: 0;
line-height: 20px;
position: absolute;
width: 100%;
}
a.has-caption img { vertical-align: bottom }
JavaScript
$('a.has-caption').on('click', function(e) {
e.preventDefault(); e.stopPropagation();
var self = $(this)
, tmpId = 'toggle-' + Date.now();
self.addClass(tmpId);
$('span.caption', self).toggle();
$('body').one('click', function(e) {
if (!$(event.target).closest('.' + tmpId).length) {
$('span.caption', '.' + tmpId).hide();
self.removeClass(tmpId);
};
});
});
http://jsfiddle.net/83s7W/

On mouseover, changing an image's opacity and overlaying text

I want to drop the opacity and overlay text on a thumbnail image when I mouse over it. I have several ideas about how to do it, but I'm fairly certain they're inefficient and clumsy.
Make a duplicate image in Photoshop with the text overlay and reduced opacity. Swap the original out for the duplicate on mouseover.
Use CSS to drop the opacity on mouseover. Use Javascript to toggle visibility of a div containing the overlay text.
The problem I see with 1 is it seems like an unnecessary use of space and bandwidth, and will cause slow load times. With 2, it seems like I'd have to hard-code in the location of each div, which would be a pain to maintain and update. I know this is a somewhat general question, but I'm at a loss about how to go about this. How can I do this relatively simple task in a way that will make it easy to add new thumbnails?
Wrap your image in a <div class="thumb">
Add position: relative to .thumb.
Add <div class="text> inside .thumb.
Add display: none; position: absolute; bottom: 0 to .text.
Use .thumb:hover .text { display: block } to make the text visible on hover.
Like this: http://jsfiddle.net/dYxYs/
You could enhance this with some JavaScript/jQuery: http://jsfiddle.net/dYxYs/1/
$('.text').hide().removeClass('text').addClass('text-js');
$('.thumb').hover(function(){
$(this).find('.text-js').fadeToggle();
});
This way, the basic effect still works without JavaScript, and users with JavaScript get the appealing fade effect.
Go with option 2. There are ways to do it to not have to write a jQuery function for each image. As seen in my jsfiddle.
http://jsfiddle.net/daybreaker/dfJHZ/
HTML
<img src="http://placekitten.com/300/300" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
<br><br>
<img src="http://placekitten.com/200/200" />
<span class="text" style="display:none">THIS IS A KITTEN</span>
jQuery
$('img').mouseover(function(){
$(this).css('opacity','.2');
$(this).next('span.text').show();
}).mouseout(function(){
$(this).css('opacity','1');
$(this).next('span.text').hide();
});
You would need to modify the span.text css to overlay it on top of the image, but that shouldnt be too bad.
Wrap it in an element and do something like this:
var t;
$('div.imgwrap img').hover(function(){
t = $('<div />').text($(this).attr('title')).appendTo($(this).parent());
$(this).fadeTo('fast',0.5);
},function(){
$(this).fadeTo('fast',1);
$(t).remove();
});
with a markup similar to:
<div class="imgwrap">
<img src="http://www.gravatar.com/avatar/3d561d41394ff0d5d0715b2695c3dcf0?s=128&d=identicon&r=PG" title="text" />
</div>
example: http://jsfiddle.net/niklasvh/Wtr9W/
Here's an example. You can position the text however you want, but the basic principle below.
http://jsfiddle.net/Xrvha/
#container { position: relative; }
#container img, #container div {
position: absolute;
width: 128px;
height: 128px;
}
#container img { z-index -1; }
#container div {
z-index 1;
line-height: 128px;
opacity: 0;
text-align: center;
}
#container:hover img {
opacity: 0.35;
}
#container:hover div {
opacity: 1;
}
If you don't want to change your HTML wraping things etc, I suggest you this way. Here is the jQuery:
$(function() {
$(".thumb").mouseenter(function() {
var $t = $(this);
var $d = $("<div>");
$d.addClass("desc").text($t.attr("alt")).css({
width: $t.width(),
height: $t.height() - 20,
top: $t.position().top
});
$t.after($d).fadeTo("fast", 0.3);
$d.mouseleave(function() {
$(this).fadeOut("fast", 0, function() {
$(this).remove();
}).siblings("img.thumb").fadeTo("fast", 1.0);
});
});
});
2 is a good solution, have done about the same as this and it isn't as hard as you would've tought;
Drop de opacity with css indeed, than position a div relative to the img, and over it. It can be done with plain css. The z-index is the trick. That div can just be shown with $('#div').slideUp() ie.

How to change the text of a div tag

I have a simple div tag. Can you please tell me how can I change the text to 'mouse in' in my onmouseover handler? and 'mouse out' in my onmouseout handler?
<div id="div1" onmouseover="alert(1);" width="100px" height="200px" border="1">
test
</div>
and why the width/height and border attributes do not work? I want to set the border to be 1 pixel with width = 100 pixels and height = 200 pixels.
Thank you.
For your CSS, add the following:
/* Using inline-block so we can set w/h while letting elements
flow around our div */
#div1 { display:inline-block;
width:100px; height:200px;
border:1px solid #000; }
For your Javascript:
/* We start wit a reference to the element via its ID */
var myDiv = document.getElementById("div1");
/* Then we add functions for our events */
myDiv.onmouseover = function() { this.innerHTML = 'mouse over'; }
myDiv.onmouseout = function() { this.innerHTML = 'mouse out'; }
Which leaves us with very clean and minimalistic markup:
<div id="div1">Hover Me!</div>
Online Demonstration
DIVs don't have the width/height/border attributes. You should use styles instead. Even better use CSS classes to style your DIV.
<style type="text/css">
.message {
width: 100px;
height: 200px;
border: solid 1px #000;
}
</style>
<div id="div1" class="message">test</div>
You might also want to consider using the jQuery hover method rather than mousein/out. While there are times that mousein/out are more appropriate, I've found that the behavior usually desired is a hover effect. This is easiest to handle in a browser-independent way with a JS framework, like jQuery.
$('#div1').hover( function() {
$(this).text('mouse in');
},
function() {
$(this).text('mouse out');
}
});
try this <div style="width:100px;height=200px;border=1px solid black" >your text</div>
to make your css work
Simply replace alert(1); with a Javascript function. You could do
this.innerHTML = 'mouse in'
and similarly for onmouseout.
As for your border problem, that is because you must you must do the following:
style="border:1px solid black"
as border is a CSS element.

Categories