so I'm trying to append image src to a div when you click on it...so far I've written it like this and it doesn't seem to work, no error reports, no idea what's going on. The image is of a class .card (there's 15 of them), and I want to append to the div only if the border is gray, you click once to select the card (changing the border) and then click again to paste the selected card onto the div...the div is called .picks. I just want to display the image src as text on my page. thanks for the help
$(".card").click(function() {
console.log("click");
if($(this).css('border')==="4px solid gray") {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if(pick<15) {
pick++;
}
else {
booster++;
pick=1;
}
}
else {
$(this).css('border', '4px solid gray');
}
});
The problem is that you rely on result of css("border") while it's not what you expect: e.g. Chrome will retrieve border styles as "4px solid rgb(128, 128, 128)".
Instead set CSS class selected and check if the card has this class or not:
$(".card").click(function () {
if ($(this).hasClass('selected')) {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if (pick < 15) {
pick++;
} else {
booster++;
pick = 1;
}
} else {
$(this).addClass('selected');
}
});
Demo: http://jsfiddle.net/1o7tgs5j/13/
In general as the rule of thumb, avoid using $.fn.css method for styling, not only this is very obtrusive but also error prone approach. In most cases usage of addClass/removeClass brings much more flexibility.
You should be using
if($(this).css('border')==="4px solid rgb(128, 128, 128)")
{
....
}
But i will suggest you to do it this way...
$(".card").click(function () {
console.log("click");
if ($(this).hasClass("clicked")) {
var cardname = $(this).attr('src');
$(".picks").append(cardname);
if (pick < 15) {
pick++;
} else {
booster++;
pick = 1;
}
} else {
$(this).css('border', '4px solid gray').addClass("clicked");
}
});
Working Fiddle
Related
I am coding a simple navigation bar for a project that has four sections, and I made it interactive enough to have a specific color when hovering/clicking on a section and then it returns back to its original color after clicking.
But what if I want the selected section to still be colored/highlighted when a user is viewing it?
So if the hovering color is coded blue, i want the section in the Navbar to still be blue when a user has selected it, and then changes when a user selects another section. Here's my code so far.
// The mouse hover functiona and commands. Here we specificy the color of the buttons/mouse
// when the user clicks on them, there's a color for hovering/clicking
// and a color for leaving the button
function mouseOver () {
let anchor = document.getElementsByTagName('a');
for (i = 0; i < anchor.length; i++) {
anchor[i].addEventListener('mouseover', function handleMouseOver() {
event.target.style.backgroundColor = "#72a6ca";
event.target.style.color = "#fff";
})
//the color returns to its normal state after clicking away
anchor[i].addEventListener('mouseout', function handleMouseOut() {
event.target.style.backgroundColor = "rgb(220, 220, 220)";
event.target.style.color = "black";
})
}
}
and here is my navbar display code
function navBarStyle () {
let anchor = document.getElementsByTagName('a');
let styles = `
display: flex;
flex-direction: row;
align-items: stretch;
color: #000;
text-decoration: none;
margin: 0 0.5em 0 0.5em;
padding: 0.5em;
background-color: rgb(220, 220, 220);
font-size: large;
transform:translateX(-0.5em);
`;
for (i = 0; i < anchor.length; i++) {
anchor[i].setAttribute('style', styles);
} }
if i was vague enough i am sorry, but any help would be appreciated to put me on the right track
Firstly, a note for your current implementation. It works and it is pretty well coded. But for this thing browsers offer native functionality using the :hover selector and it would be better to use than to reinvent it.
I don't have your HTMl but you would most likely need to add a class to each 'a' tag in the nav, something like this:
<nav>
Link 1
Link 2
</nav>
and then you would need a style tag in the head (or better, external css)
<head>
...
<style>
.nav-link {
background-color: 72a6ca;
color: #fff;
}
.nav-link:hover {
background-color: rgb(220, 220, 220);
color: black;
}
</style>
</head>
As for the current section, your best bet would be to use https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
See here for an example: Intersection observer API scroll aware navigation
or this codepen: https://codepen.io/mishunov/pen/opeRdL
Using IntersectionObserver you can detect when the user scrolls in/out of the section. You can toggle another class on and off of the related nav-link then. For example - say you toggle the .current class, your style could look like this to style both cases (hovering and currently scrolled) in 1 place:
.nav-link:hover,
.nav-link.current {
background-color: rgb(220, 220, 220);
color: black;
}
You can make a class named active like this
.active {
backgroundColor: #72a6ca;
color: #fff;
}
and assign it to each anchor that's clicked(or hovered), simultaneously remove .active from the other anchors
let anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
anchor.addEventListener('mouseover', function handleMouseOver() {
const target = event.currentTarget;
if (target.classList.contains('active')) {
target.classList.remove('active')
} else {
[...anchors].forEach((anchor) => anchor.classList.remove('active'))
target.classList.add('active')
}
})
}
If you want to give the class active to the anchors in viewPort use this code:
const anchors = document.getElementsByTagName('a');
const isInViewport = el => {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
const run = () =>
anchors.forEach(item => {
if (isInViewport(item)) {
item.classList.add('active');
}
});
// Events
window.addEventListener('load', run);
window.addEventListener('resize', run);
window.addEventListener('scroll', run);
I haven't been able to make this code work. From bottom to top, it seems to work perfectly fine - that is, I drag a div element and then drop it on top of another, and it does what it is intended to do. However, when I try to swap an element with another below it, no swap occurs, and that's what's been baffling me most. Could you please shed some light on why it's not working?
let thing1 = document.getElementById("thing1");
let thing2 = document.getElementById("thing2");
let thing3 = document.getElementById("thing3");
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("id", ev.target.id);
console.log(ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var thing = document.getElementById(ev.dataTransfer.getData("id"));
var thingParent = thing.parentElement;
var tgt = ev.currentTarget;
console.log(thing)
console.log(tgt)
thingParent.replaceChild(thing, tgt);
thingParent.appendChild(tgt);
}
thing1.addEventListener("drop", drop);
thing2.addEventListener("drop", drop);
thing3.addEventListener("drop", drop);
thing1.addEventListener("dragover", allowDrop);
thing2.addEventListener("dragover", allowDrop);
thing3.addEventListener("dragover", allowDrop);
thing1.addEventListener("dragstart", drag);
thing2.addEventListener("dragstart", drag);
thing3.addEventListener("dragstart", drag);
.thing {
width: 100%;
height: ;
background: red;
}
.drag {
background: red;
height: 50px;
margin: 10px;
text-align: center;
}
#thing1 {
background: yellow;
}
#thing2 {
background: blue;
}
<div id="thing">
<div id="thing1" class="drag" draggable="true">1</div>
<div id ="thing2" class="drag" draggable="true">2</div>
<div id ="thing3" class="drag" draggable="true">3</div>
</div>
You are always appending the div to be replaced at the bottom of the page, which means you can never actually replace the div at the bottom. I added timeouts to your code to show you what is happening here. (Note that I added a removeChild call, but this happens automatically before the operation replaceChild, so I just made it explicit to enhance your ability to visualize what is happening.)
The solution isn't simple, because whether the choice to insert before or after an element is going to depend on whether you are coming from below or above. One easy solution is swap the two elements out for each other. This can be done by cloning one, as shown below:
function drop(ev) {
ev.preventDefault();
var thing = document.getElementById(ev.dataTransfer.getData("id"));
var tgt = ev.currentTarget;
if (thing && tgt) {
var thingParent = thing.parentElement;
var newTgt = tgt.cloneNode(true);
addListeners(newTgt);
thingParent.replaceChild(newTgt, thing)
thingParent.replaceChild(thing, tgt);
}
}
function addListeners(el) {
el.addEventListener("drop", drop);
el.addEventListener("dragover", allowDrop);
el.addEventListener("dragstart", drag);
}
Even if you decide you actually want a different behavior, knowing how to swap two elements should give you the tools to get whatever behavior you want.
I want to now if it is possible to override an background image with another color? In my case I want to create 4 checkboxes dynamically, and when these checkboxes are checked I want the color of the input field changed. I have tried to fix it by the code below, but it seems to not work.
Live Demo
Jquery:
var $div = $('<div />')
$('<input/>', {
"type": "text",
"class": "checkBoxCard"
}).appendTo($div);
$("#Getbtn").on("click", function () {
CheckBoxesChecked();
$('#modalDialog').dialog("close");
});
function CheckBoxesChecked() {
var numAll = $('input[type="checkbox"]').length;
var numChecked = $('input[type="checkbox"]:checked').length;
if (numChecked == numAll) {
$('.checkBoxCard').css("background-color", "yellow");
}
}
CSS:
.checkBoxCard {
background-image: url(http://static3.depositphotos.com/1004899/246/i/950/depositphotos_2465679-Cream-handmade-sheet-of-paper.jpg);
}
This will work for modern browsers, IE9+:
.checkBoxCard {
background: #eee url(img.png) 0 0 no-repeat;
}
.checkBoxCard:checked {
background-image: none;
background-color: yellow;
}
I'm trying to change the background image of a div when a user hovers over and clicks it. I'm stuck on limiting the images from changing to ONLY the element on which the user is hovering/clicking. In this example, all of the buttons will change when one div is hovered on/clicked. This is something I'm trying to replicate that's already working in jQuery. I'm guessing it's possible to use "this" but all of the ways I've tried so far result in errors.
Bonus points for anyone who cal tell me why the alert happens on page load in Firefox but not IE or Chrome
JavaScript
var buttons = document.getElementsByTagName('div');
var i;
function iconDown(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -61px';
}
}
function iconUp(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOver(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px -122px';
}
}
function iconOut(e) {
for (i=0; i<buttons.length; i++) {
buttons[i].style.backgroundPosition = '0px 0px';
}
}
function processAction() {
alert("Working!");
}
function Init () {
for (i=0; i<buttons.length; i++) {
if (document.addEventListener) { // all browsers except IE before version 9
buttons[i].addEventListener ("mousedown", iconDown, false);
buttons[i].addEventListener ("mouseup", iconUp, false);
buttons[i].addEventListener ("mouseover", iconOver, false);
buttons[i].addEventListener ("mouseout", iconOut, false);
buttons[i].addEventListener("click", processAction, false);
}
else { // IE before version 9
buttons[i].attachEvent ("onmousedown", iconDown);
buttons[i].attachEvent ("onmouseup", iconUp);
buttons[i].attachEvent ("onmouseover", iconOver);
buttons[i].attachEvent ("onmouseout", iconOut);
buttons[i].attachEvent("onclick", processAction);
}
}
}
Init();
CSS
.btn {width:100px; height:61px; float:left;}
#BackImg {background: url('images/Back.gif') no-repeat 0px 0px;}
#NextImg {background: url('images/Next.gif') no-repeat 0px 0px;}
HTML
<DIV class="btn" ID="BackImg"></DIV>
<DIV class="btn" ID="NextImg"></DIV>
You don't need any javascript for this. Just use css.
.specialClassyClass{
/*default background position*/
}
.specialClassyClass:hover{
/*hover state background position*/
}
.specialClassyClass:active{
/*mouse down background position*/
}
For the clicky stuff:
var whatever = function(el, ev, handler){
el.attachEvent?
el.attachEvent(ev, handler):
el.addEventListener(ev, handler, false);
}
whatever(button[i], 'click', processAction);
You can use this:
function processAction(e) {
var active = document.querySelector('.active'); // get currently active button
if(active != undefined)
active.className = "btn"; // remove active class
e.target.className = 'btn active' // add active class to clicked element
}
then your css can be something like:
.btn {width:100px; height:61px; float:left;background: orange;}
.active {background: red;}
http://jsfiddle.net/NXVv7/
I'ld like to change the "imgTag.style.border='5px solid #FF00FF'" to black when the mouse is over an image.
This is my JavaScript:
javascript:for(i=0;i<document.getElementsByTagName('img').length;i++)
{
var imgTag=document.getElementsByTagName('img')[i];
imgTag.style.border='5px solid #FF00FF';
imgTag.title='';
imgTag.onclick=function()
{
return !window.open('http://www.example.com/#/'+this.src);
}
}
void(0)
How can it be done?
Thanks
Frank
You need to bind handlers to the mouseover and mouseout events to change the image's border color:
var imgs = document.getElementsByTagName('img');
for(var i = 0; i < imgs.length; ++i) {
imgs[i].onmouseover = function() {
this.style.borderColor = '#000';
};
imgs[i].onmouseout = function() {
this.style.borderColor = '#f0f';
};
}
For example: http://jsfiddle.net/bNk4Y/
Not sure what's wrong with the code you have, but if i understand your question correctly, this should do it:
HTML:
<img src="" >
<img src="">
...
JS:
var imgs = document.getElementsByTagName("img");
for(i=0;i<imgs.length;i++)
{
imgs[i].onmouseover = function() {this.style.border="1px red solid";};
}
Note, however, that this can easily be achieved with CSS as well, which is a better practice - in case users have JS disabled, etc
img:hover {
border: 1px red solid;
}