Change Link BG Color onClick - javascript

I want to change the BG color of a link when the user clicks on it/onClick. Here is the code I am currently working on;
Link Drop Down
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
document.getElementById("dropbtn").onclick = function()
{
this.style.background = '#FFF';
}
}
But it didn't worked and I am not sure why.

Link Drop Down
function myFunction() {
document.getElementById("dropbtn").onclick = function(event) {
var drop_down = document.getElementById("myDropdown");
if (!drop_down.classList.contains('show')) {
drop_down.classList.add('show');
this.style.background = '#FFF';
}
else {
drop_down.classList.remove('show');
this.style.background = '';
}
return true;
}
}
myFunction();
Basically you have to install the onclick Event handler (see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers) , which receives an event parameter with event info. this inside it actually points to the element with id=dropbtn, so you can either reference it directly as in your question or get the reference that is on event.target.
EDIT
Actually I was wrong, sorry, this indeed points to the element clicked. Fixed the answer.

Try this:
Link Drop Down
function myFunction(e) {
document.getElementById("myDropdown").classList.toggle("show");
e.target.style.background = '#FFF';
}

Related

Disable dragging in HTML webpage

I'm trying to make an etch-a-sketch with HTML where I have a div container with lots of div elements in it, using grid display in CSS.
HTML: <div id="canvas"></div>
Then I use JS to add the div elements:
for(let i =1;i<=256;i++){
let squareDiv = document.createElement("div");
canvasElement.appendChild(squareDiv);
canvasElement.setAttribute("draggable","false");}
The draggable attribute doesn't work.
When I click and drag to draw something, it is dragging a faint image as below:
Is there an attribute I could use to disable this ?
Edit: All javascript code:
canvasElement =document.getElementById("canvas")
let isToggling = false;
function enableToggle(e) {
isToggling = true;
}
function disableToggle() {
isToggling = false;
}
function toggle(e) {
if (isToggling === false) {
return;
}
console.log('toggle:', e.target);
e.target.classList.add('red');
}
for(let i =1;i<=256;i++){
let squareDiv = document.createElement("div");
canvasElement.appendChild(squareDiv);
canvasElement.setAttribute("draggable","false");
squareDiv.onmousedown=enableToggle;
squareDiv.onmouseenter=toggle;
squareDiv.onmouseup=disableToggle;
}
You can use e.preventDefault() to prevent the default effect from happening inside your onmousedown event.
Add e.preventDefault() inside your enableToggle(e) function
function enableToggle(e) {
isToggling = true;
e.preventDefault()
}
If that doesn't work add it to toggle() and disableToggle()
I had your exact issue with Etch-A-Sketch and this is how I did it: similar to the other user's answer, this also uses preventDefault() but this activates using the ondragstart HTML attribute.
First, use this JS function to enable preventDefault().
function dragstart (event) {
event.preventDefault()
}
Next, apply dragstart (event) to all your elements in your etch grid. In my case, I used the spread syntax [...nodeList] with the forEach method in a function which runs immediately after generating my grid squares.
let grid = document.getElementById('grid');
function addSquare () {
let sliderValue = document.getElementById('slider').value;
for (let i = 0; i < sliderValue ** 2; i++) {
const square = document.createElement('div');
square.className = 'square';
grid.appendChild(square);
}
}
function modifyGridProperty () {
let square = [...document.getElementsByClassName('square')];
square.forEach(element => {
element.setAttribute('ondragstart', 'dragstart(event)');
});
}

How to turn on/off a function on a button click?

I have been working in a mini-game-project (Simons game) that many of you may know. Where the computer plays a random sequence of buttons in which players have to follow to go to the next level in the game e.g: [one click first round, two clicks second round..].
I already did all the button effects as well as make the machine plays buttons randomly in a range of ten rounds. So, what I would like to do is use a button to turn on and off the function that makes the computer clicks By Itself using a button.
I already tried using the jQuery function $(startButton).on('click', clickByItself); alone but it did not worked.
$(document).ready(function() {
//four variables representing its button effects
//button blue effect
var blueButtonEffect = code here;
var greenButtonEffect = code here;
var redButtonEffect = code here;
var yellowButtonEffect = code here;
//to be used on the buttonEffects()/clickByItself()
var arr = [blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect];
let enabled = true;
let times = 0;
//makes button effects play itself randomly
function clickByItself() {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled == true) { //TRYING TO TURN ON/OFF THE FUNCTION ON BUTTON CLICK..
$(startButton).on('click', clickByItself);
}else{
$(startButton).on('click', clickByItself);
}
}
Now, I am trying to use a function turnOnTurnOff() to see whether I could do the effect of turning on and off with the click of a the startButton. Thank you.
You can use .off() method of jQuery to remove an event listener as follows.
I added two divs for better demonstration.
One button binds and unbinds (toggles) the click handler of the second button using jQuery's .on() & .off(). When the click handler is bound to the second button, clicking it will update the div with a number. When the click handler is unbounded from the second button, clicking the second button will do nothing. Two lines of interest in the JavaScript code below are decorated with a comment each. The rest is for demonstration.
window.enabled = false;
window.count = 1;
// Initialize the view (for demo)
$(function() {
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You CANNOT click me');
});
// Toggle click functionality using jQuery's .on() & .off() methods
function toggle() {
enabled = !enabled;
if (enabled) {
// Line of interest #1: jQuery .on()
$('#btn').on('click', handleClick);
} else {
// Line of interest #2: jQuery .off()
$('#btn').off('click', handleClick);
}
$('#switchIndicator').html(`<p>${enabled ? 'Switch is ON' : 'Switch is OFF'}</p>`);
$('#btn').html(enabled ? 'You can click me :-)' : 'You cannot click me :-((');
$('#btn').removeClass(enabled ? 'disabled' : 'enabled').addClass(enabled ? 'enabled' : 'disabled');
}
function handleClick() {
$('#counter').append(` ${count++}`);
}
/* CSS */
#btn.enabled {
background-color: greenyellow;
}
#btn.disabled {
background-color: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="switchIndicator"></div>
<button id="switch" onclick="toggle()">On/OFF Switch</button>
<button id="btn"></button>
<div id="counter"></div>
Give this a try:
function clickByItself() {
if(enabled) {
let random = Math.floor(Math.random() * arr.length);
$(arr[random]).click();
if (++times < 10) {
setTimeout(function() { clickByItself(times); }, 1000);
}
}
}
clickByItself();
function turnOnTurnOff() {
if (enabled) {
enabled = false;
} else {
enabled = true;
clickByItself();
}
}
$(startButton).click(function() {
turnOnTurnOff();
});
You could do it in multiple ways. One is to use setInterval instead of setTimeout and store it inside a variable. When you need to stop it, just call clearInterval.

How to unbind within a bind event

I am developing a feature in a chrome extension that allows the user to hover over and detect any element on the page. A select button on the top right of the page activates the feature. Whenever an element is clicked on, an input box near the button gets filled with that element's innerHTML. After the click, the selection should stop and clicking will no longer be recognized by the feature. Everything works fine but I am unable to unbind the clicking event. Is there anything wrong with my code? Please let me know
content.js
window.onload = () => {
var highlight = function (event){
if(!$(event.target).is("#home_container *")){
event.target.style.backgroundColor = "rgba(121, 204, 255, 0.4)";
}
}
var remove = function (event){
if(!$(event.target).is("#home_container *")){
event.target.style.backgroundColor = "";
}
}
var disableLinks = function (event){
event.preventDefault();
}
var highlightProcess = function(event) {
$('a').bind("click", disableLinks);
$(document).bind("mouseover", highlight);
$(document).bind("mouseout", remove);
$(document).bind("click", (elem) => {
if(!$(elem.target).is("#home_container *")){
$("#input_box").val(elem.target.innerHTML);
remove(elem);
$(document).unbind("mouseover", highlight); //<-- works
$(document).unbind("mouseout", remove); //<-- works
$('a').unbind("click", disableLinks); //<-- works
$(this).unbind("click"); //<-- this does not work
}
});
}
document.getElementById('st_select_element_button').addEventListener("click", highlightProcess);
}
You can change the highlightProcess to arrow function and then 'this' will refer to the document :
var highlightProcess = (event) => {...}
Solved
changed
$(this).unbind("click");
to
$(document).unbind("click");

Javascript click event requires double clicks

I have a simple HTML-CSS-JavaScript page with an event listener on a button to toggle a div.
However, all is working but the animation function takes two clicks first time to work, although i consoled the click event to prove that the button listens to the first click too.
i tried to wrap into window.onload but same thing.
note: i want to use pure javascript only.
thank you
this pic shows the first click (it says "clicked" in the console):
this pic shows the second click (animation took place):
Here is my code:
var showDivButton = document.getElementById('showDivButton');
var info = document.getElementById('info');
showDivButton.addEventListener('click', animation) ;
// animation func
function animation () {
console.log('Clicked!');
if (info.style.display === 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
Look at My Plunker Here please. Thank you in advance.
Try to revise your function block as follow:
function animation () {
console.log('Clicked!');
if (info.style.display == '' || info.style.display == 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
info.style.display is '' on initial
Because info.style.display refers to the style attribute of your div, not the computed Style, so on the first click, this is not set.
You may want to look at getComputedStyle, but i would advise switching class instead of directly modifying style.

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

Categories