Keep an image selected - javascript

I have a program which allows the user to select some images and i gave them the pseudo class
.my_image_clas:hover{
border:3px solid blue;
-webkit-box-sizing: border-box; }
to make them surrounded with borders when the pointer goes over (giving a "selected effect"). I'd like to keep this effect even when i select the image, like this :
How can i achieve this? (With javascript)

CSS-only "hack"
At first this question asked for CSS-only solution and while, as others have said, it's not really possible to achieve what you ask for without JavaScript, there is a CSS-only hack, however:
img {
margin: 3px;
width: 100px;
}
img:hover, img:target {
border: 3px solid green;
margin: 0;
}
<img id="a" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" />
<img id="b" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" />
It works by making your images a target of a click on an anchor they are contained in. We can style elements that are link targets, because we have a selector for that in CSS.
Note that this way you can select only one image.
Pure JavaScript
If you want to do it with JavaScript though, you can use below code:
function select(element) {
element.onclick = function() {
element.classList.toggle('selected');
}
}
Array.from(document.getElementsByClassName('selectable')).forEach(select);
img {
margin: 3px;
}
.selected {
border: 3px solid green;
margin: 0;
}
<img class="selectable" src="https://farm1.static.flickr.com/640/23366158776_3bddebe005_t.jpg" />
<img class="selectable" src="https://upload.wikimedia.org/wikipedia/commons/3/3c/Marsglobe_tiny2.jpg" />
It works by toggling class named selected on click for every element with class selectable. Also, it will let you select multiple items.
If you want to limit the user to selecting only one element though, change the above JavaScript to:
function select(element) {
element.onclick = function() {
var selected = document.getElementsByClassName('selected')[0];
if (typeof selected !== 'undefined') { selected.classList.remove('selected'); }
if (element !== selected) { element.classList.add('selected'); }
}
}
Array.from(document.getElementsByClassName('selectable')).forEach(select);

You may use jQuery here for hovering effects, jQuery provides the hover() pseudo-event, which behaves better than moueseenter/mouseleave. Also, it's a good idea to create a CSS class for each state (normal and hovered), and then change the class on hover:
$(document).ready(function() {
$(".my_image_clas").hover(
function() { $(this).addClass("Hover"); },
function() { $(this).removeClass("Hover"); }
);
});
.my_image_clas.Hover { border: 3px solid blue; }
#Francesco Monti I've read your comment.
for working with jquery you may add jquery.js under the head tag of your html
<head>
<script src="jquery-1.12.0.min.js"></script>
</head>
or adding online would be
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
and you can use $(document).ready(function() under the script tags.
If you want you can separate js & css files and includes those files accordingly.

Your approx CSS:
.item {
box-sizing: border-box;
border: 2px solid transparent;
}
.item.selected,
.item:hover,
.item:focus {
border: 2px solid blue;
}
Some basic jQuery:
$('.item').on('click', function (event) {
event.preventDefault(); // Prevent default behavior if .item is a link or button
$(this).toggleClass('selected');
})

Related

How to add loading spinner in textbox as I start typing in it?

How to add a loading spinner in the textbox as I start typing in it and once the max-length is achieved a green tick mark will be displayed in the place of loading spinner.
I am doing this in my ionic app.
I have partially tried it, but don't know how to complete it. May be jquery is needed but I don't have much knowledge about that.
Here is my code:
<input id='inputsource' maxlength="10" />
css:
.loadinggif {
background:url('img/ajax-loader.gif') no-repeat right center;
}
.greentick {
background:url('img/greentick.png') no-repeat right center;
}
Maybe you could try this (sinnce I don't have access to your images, I just used border color to indicate state):
$('#inputsource').on('keydown', function() {
$(this).addClass('loadinggif');
})
.on('blur', function() {
$(this).removeClass('loadinggif');
})
.on('keyup', function() {
var $this = $(this);
if ($this.val().length >= 10) {
$this
.removeClass('loadinggif')
.addClass('greentick');
} else {
$this.removeClass('greentick');
}
});
.loadinggif {
background: url('img/ajax-loader.gif') no-repeat right center;
border: 1px solid tomato;
outline: none;
}
.greentick {
background: url('img/greentick.png') no-repeat right center;
border: 1px solid yellowgreen;
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='inputsource' maxlength="10" />
You can't add an image to the actual input so your html might appear as
<input id='inputSource'><div id='inputSourceIndicator'></div>
You will also need to add a function to call with each keypress
<input id='inputSource'><div id='inputSourceIndicator' onkeyup='myFunc(this.value);></div>
Your JS function would be
function myFunc( value ) {
// do check of whatever
// if check is false
// change the class of the indicator
document.getElementById('inputSourceIndicator').className = "loadinggif";
// otherwise show the other class
document.getElementById('inputSourceIndicator').className = "greentick";
Your css would also need to include
#inputSourceIndicator {
width: 16px;
height: 16px;
display: inline-block;
}
Or something along those lines :-)

Blog / Message - How do I fix that empty message divs will piling on / next to each other and make the close button work?

So I'm making a sort of blog posting system or TODO list, however you want to call it.
I want that the following can happen / is possible:
[Working] The user types something in the textarea
[Working] The user clicks on the button.
[Working] A new div will be created with the text of the textarea.
[Working] The textarea will be empty.
[Not Working] The user has got the choice to delete the post by clicking the 'X' on the right side of each '.post' div.
BUT: If I click on the button when there's nothing in the textarea, there appears an empty div, with only an 'X' close button, no background color either. They appear on the same line as the previous message, so you can get a lot of 'X's next to each other.
AND: Clicking the 'X' close button doesn't do anything. No errors in Firefox console.
If it's not clear enough, run this JSFiddle, click the button and I think you'll understand what I mean:
JSFiddle
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<script src="jquery.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div id="blog">
<h1>Blog post application</h1>
<div id="post-system">
<textarea id="poster" rows="5" cols="50" placeholder="Update status."></textarea>
<div id="button">Post</div>
<div id="posts">
</div>
</div>
</div>
</body>
</html>
jQuery Script:
<script>
$(document).ready(function () {
$('#button').click(function () {
var text = $('#poster').val();
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('.close-post').click(function () {
('.close-post').parent().hide();
});
});
</script>
CSS:
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
#blog {
background-color: blue;
margin: 50px;
padding: 50px;
text-align: center;
border-radius: 10px;
color: white;
display: block;
}
#poster {
color: default;
resize: none;
border: 1px solid black;
text-decoration: blink;
font-size: 20px;
display: inline-block;
position: relative;
border-radius: 5px;
border: 2px solid black;
padding-left: 10px;
padding-top: 5px;
}
#button {
background-color: #00FFFF;
color: white;
border: 2px solid white;
border-radius: 5px;
cursor: pointer;
width: 50px;
float: left;
}
.post {
background-color: white;
color: blue;
margin-top: 20px;
width: auto;
display: block;
}
.close-post {
margin-right: 10px;
float: right;
color: red;
cursor: pointer;
}
You appear to have two issues:
1) You don't want a post to be created if the textarea is empty
Simple fix . . . check to see if it is empty, before calling the logic to add the new post (and use jQuery's $.trim() to account for only blank spaces):
$('#button').click(function() {
var text = $.trim($('#poster').val());
if (text !== "") {
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
}
});
2) The 'X' buttons are not closing the posts
This also should be a pretty easy fix . . . the reason that they are not working is because the 'X' buttons don't exist when the page is loaded so $('.close-post').click(function() { is not binding to them on page load. You will need to delegate that event binding, so that it will apply to the 'X' buttons that are dynamically added after the page is loaded.
Now, not knowing what version of jQuery that you are using (I can't access jsFiddle from work), I'll point you to the right place to figure out the correct way to do it: https://api.jquery.com/on/
If it is jQuery 1.7 or higher, you would do it like this:
$("#posts").on("click", ".close-post", function() {
$(this).parent().hide();
});
If your version is earlier than that, then investigate the jQuery .delegate() and .live() methods to determine which is the right one to use for your code..
Try this:
$(document).ready(function() {
$('#button').click(function(event) {
event.preventDefault();
var text= $('#poster').val();
if (text === '') {
alert('Nothing to post!');
return;
}
$('#posts').prepend("<div class='post'>" + text + "<span class='close-post'>×</span></div>");
$('#poster').val('');
});
$('#posts').on('click', '.close-post', function() {
$(this).closest('.post').fadeOut();
});
});
JSFiddle
The way you are doing this, the user will only ever see what they are posting - if you're trying for a chat type where users talk to each other then you will need to store what is being typed on the server side and refresh the screen using something like ajax
but in response to your question, you need to bind the close click like this:
$( "#posts" ).on( "click", ".close-post", function() {
$(this).parent().hide(); // $(this) is the clicked icon, the way you did it above wouldn't as if it had the dollar, it would close all .close-post parents
});
See the part about delegated events: http://api.jquery.com/on/

Advice about my jQuery script + compatibility with iDevices

I posted a question about a script but I have another question about another script.
I have two blue buttons at the beginning that turn gray on a roll-over.
Blue becomes (and remains) gray when you click on one of the two buttons.
Both buttons must not be blue both. Each button brings up a form at a time (form contact and form quotation).
I have wrote this and I would to know if I can simplify it ?
How to make the "toggle" function compatible with iDevices (iPad, iPhone...) ?
Thank you in advance.
$(function() {
$("#form-contact").hide();
$("#form-devis").hide();
$("#btn-contact").click(function(){
$(this).toggleClass("btn-form-hover");
$("#form-contact").fadeToggle(500, "linear");
$("#form-devis").hide();
$("#btn-devis").removeClass("btn-form-hover");
});
$("#btn-devis").click(function(){
$(this).toggleClass("btn-form-hover");
$("#form-devis").fadeToggle(500, "linear");
$("#form-contact").hide();
$("#btn-contact").removeClass("btn-form-hover");
});
});
This looks about as simple as you can get for forcing only one button to have the "selected" state. If you need to do this for many elements, see my code below.
Toggle should work on iDevices as long as the jQuery library you included supports it. However, you will not get a hover effect on iDevices since there is no mouse.
Code Example:
If you plan to do this frequently with buttons (rocker switches) where only one element can have the "selected" state you could make a function like this:
CodePen: http://codepen.io/Skrypt/pen/dyCha
HTML
<div class="rockerSwitch myRocker1">
<button class="left">On</button><button class="right">Off</button>
</div>
<div class="rockerSwitch myRocker2">
<button class="left">True</button><button class="right">False</button>
</div>
<div class="rockerSwitch myRocker3">
<button class="left">Option 1</button><button class="right">Option 2</button>
</div>
CSS
.rockerSwitch button {
background-color: #dcffb2;
border: 1px solid #87cf30;
cursor: pointer;
outline: 0;
}
.rockerSwitch button.left {
margin-right: 0px;
border-radius: 5px 0px 0px 5px;
}
.rockerSwitch button.right {
margin-left: 0px;
border-radius: 0px 5px 5px 0px;
}
.rockerSwitch button:hover {
background-color: #fff;
}
.rockerSwitch button.selected {
background-color: #87cf30;
}
JS/jQuery
$(function() {
$('.myRocker1').rockerSwitch();
$('.myRocker2').rockerSwitch();
$('.myRocker3').rockerSwitch();
});
$.fn.rockerSwitch = function() {
var left = $('.left', this);
var right = $('.right', this);
left.on('click', function() {
left.addClass("selected");
right.removeClass("selected");
});
right.on('click', function() {
right.addClass("selected");
left.removeClass("selected");
});
}

jquery blind and exposing child div behind?

I'm trying to achieve the effect of a sliding div using the jquery animate option. I'm able to "slide" the parent div up but I'm having issues with showing the div behind the slider.
I've created this jsfiddle to show my issue.
Try uncommenting the photoOptions div. I'm trying to hide this div so it's only revealed when the parent div is slid up.
<div class="photoWrapper">
<!-- <div class="photoOptions"> This is your data. </div>-->
<div class="photoHolder">
Image Here
</div>
<div class="photoMeta">More data here</div>
<div class="photoCredits">
Trigger
</div>
</div>
Code
jQuery.fn.blindToggle = function(speed, easing, callback) {
var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
return this.animate({
marginTop: parseInt(this.css('marginTop')) < 0 ? 0 : -h
}, speed, easing, callback);
};
$(document).ready(function(){
$(".trigger").click(function(){
$('.photoHolder').blindToggle('slow');
});
});
Current CSS:
.photoWrapper {
width:200px;
border: solid 1px #ddd;
}
.photoHolder {
border: solid 1px #eee;
width:200px;
height:266px;
}
.photoOptions {
padding-top: 50px;
height: 266px;
width: 200px;
background: #eee;
position:absolute;
}
Any thoughts on how I can achieve this?
The browser renders elements based on there place in the DOM, if an element preceeds another element in the dom, it is rendered under it.
To change this default behaviour, you should use the CSS rule z-index, by defining a lower z-index on your .photoOptions div, it will be rendered below it.
as seen in this fiddle
Also be aware that z-index values may be handled differently for elements that are positioned absolute, due to the fact that they are not rendered in the normal flow.
Using the callback on .blindToggle() can achieve that effect but you're going to have to edit your CSS so that .photoCredits is visible and just start off with .photoOptions hidden:
$(document).ready(function () {
$(".trigger").click(function () {
$('.photoHolder').blindToggle('slow', function () {
$(".photoOptions").show();
});
});
});
.photoOptions {
padding-top: 50px;
height: 266px;
width: 200px;
background: #eee;
position:absolute;
display:hidden;
}

How do I hide CSS until a function runs?

I have a basic function that when no answer is clicked it shows an error message in
the div id "error". this works fine but when i have a background colour and image is shows the style on the div. i'm using jquery and moo tools,
Is there a way to hide this style until the answer is set.
<style type="text/css>
#error {
border: 1px solid;
margin: 10px 0px;
padding:15px 10px 15px 50px;
background-repeat: no-repeat;
background-position: 10px center;
color: #D8000C;
background-color: #FFBABA;
background-image: url('../images/error.png');
}
</style>
<div id="error"></div>
<script type="text/javascript>
function showAnswerAlert() {
$('error').set('html', '<strong>Please select an answer above.<strong>')
}
function clearErrorBox() {
$('error').set('html','');
}
</script>
Hide the div initially and show in showAnswerAlert or where ever you need
<div id="error" style="display:none"></div>
function showAnswerAlert() {
$('error').set('html', '<strong>Please select an answer above.<strong>');
$('error').show();
}
or hide error div on document ready
$(function(){
$('error').hide();
});
the reason why hide() and show() dont work is because those ase jQuery functions, if you're using mootools, and would like to use "hide()" and "show()" you need to write functions like so:
window.addEvent('domready', function() {
Element.implement({
//implement show
show: function() {
this.setStyle('display','');
},
hide: function() {
this.setStyle('display','none');
}
});
});
or you can do this to show:
$('error').setStyle('display','block');
and this to hide:
$('error').setStyle('display','none');
Sounds like this is a validation on a select item.
Validation can be done in many ways buti suggest you look t HTML5 valiations, this might be all you need:
http://diveintohtml5.info/forms.html

Categories

Resources