onload button in javascript - javascript

Via the link: http://boukestar.nl/ani-map/ you can see that I've set up a vector svg map that is animated.
My only problem is that I dont no how to deactivate or onload a button / country when you click on a other button / country. All the buttons stay active when you click on a other button.
That results in not correct information from a country that's loaded.
HTML
<button class="usa" onClick="usa()" class="hidden">Verendigde Staten</button><div id="landusa" class="hide"><img src="svg/infovs.svg" viewBox="0 0 1087 841.89"></div><div id="div1" style="display: none;"></div>
JS
(function() {
'use strict';
var svg,
button;
document.addEventListener('DOMContentLoaded', function init() {
button = document.querySelector('.usa');
svg = document.querySelector('svg');
button.addEventListener('click', clickHandler, false);
});
function clickHandler(e) {
svg.classList.toggle('usa');
e.target.classList.toggle('on');
}
}());
Has anybody an idea?
Many thanks!
Bouke

Here's my solution. If you put your code in a JSFiddle or CodePen then I can test it:
<script>
document.addEventListener("DOMContentLoaded", function init(){
var svg = document.querySelector("svg"),
currentCountry,
currentButton;
function toggle(clickedButtonCountry){
var clickedButton = document.querySelector("." + clickedButtonCountry);
currentButton.classList.remove("on");
clickedButton.classList.add("on");
clickedButton.classList.remove("hidden");
currentButton.classList.add("hidden");
svg.classList.remove(currentCountry);
svg.classList.add(clickedButtonCountry);
currentCountry = clickedButtonCountry;
currentButton = clickedButton;
}
});
</script>
<button class="usa hidden" onClick="toggle('usa')">Verendigde Staten</button>
<button class="brazil hidden" onClick="toggle('brazil')">Brazil</button>
<svg></svg>
This way Javascript "remembers" which country is currently displayed, and then when someone clicks on a button it "remembers" that country instead.
Some things to keep in mind:
usa() means you have function usa(){} somewhere, which you don't (and shouldn't). I think you were going for something like toggle('usa')
You can have multiple classes in one class attribute, like <div class="foo1 bar2"></div>
document.querySelector only returns one element. document.querySelectorAll returns many.
Using classList.toggle can get a little weird because it's not specific about whether the class should be added or removed. I prefer to explicitly use classList.add and classList.remove. classList.contains is very useful.

Related

Get variables from button css in Javascript and use them as id

Hi I need a bit of help modifying my script. What I want to do:
I have a small and easy script. It changes the class of an container so I have influence on the behaviour and looking of the container. In my scenario the buttons open a div with a music player.
My problem is that I need to declare all buttons as a script. The button ID is in my case the onclick function (see code).
So when I have 10 or twenty links I need also everytime to modify the script. My idea is to have a script wich gets feed their variables by id's and classes of containers. So I need not to modify the script file.
// JavaScript Document
function AudioFF() {
var FFplayer = document.getElementById(x);
if (FFplayer.classList.contains("audio-hidden")) {
FFplayer.classList.remove("audio-hidden");
FFplayer.classList.add("audio-shown");
} else {
FFplayer.classList.remove("audio-shown");
FFplayer.classList.add("audio-hidden");
Array.prototype.slice.call(document.querySelectorAll('audio')).forEach(function(audio) {audio.pause();});
}
};
dbbtn.onclick = function() {
x = "deepblue";
AudioFF();
};
swbtn.onclick = function() {
x = "spacewalk";
AudioFF();
};
fbtn.onclick = function() {
x = "forest";
AudioFF();
};
drbtn.onclick = function() {
x = "dreamrhythm";
AudioFF();
};
My idea was to use the same class of a button as an id for the container who needs to fade in with a string. The button has e.g. the class btn_a, btn_b … etc. The containers has the id btn_a, btn_b … I wanted the script to catch the class of the button and use this classname as a variable for getElementById. The closebutton is also using the same script to close the container. Thanks for help :-)
I will recommend to use data attribute instead
example like this:
//register listener like this
var btns = document.querySelectorAll('[data-music]');
btns.forEach(function(elm) {
elm.addEventListener('click', function(e) {
//your function
console.log(this.dataset.music);
})
})
<!--your links-->
<div id="m1"></div>
<div id="m2"></div>
<div id="m3"></div>
<!--just add data-music attribute make it the same with your div id and all set-->
<button data-music="m1">play m1</button>
<button data-music="m2">play m2</button>
<button data-music="m3">play m3</button>
You should be able to set a data tag attribute to the buttons and just read the variable from that:
<button id="myButton" data="variableForMyButton" />
document.getElementById(myButton).onClick = function(e){
x = e.target.getAttribute('data')
}
If multiple params are required you add additional data tags:
<button id="myButton" data="variableForMyButton" data-action="someSweetAction" />
Thanks guys, that was what I was looking for. My function is now like this:
The play button and closebutton are working.
<button data-music="m1">Deep Blue</button>
<div id="m1">Container Content</div>
var btns = document.querySelectorAll('[data-music]');
btns.forEach(function(elm) {
elm.addEventListener('click', function(e) {
//function
var FFplayer = document.getElementById((this.dataset.music));
if (FFplayer.classList.contains("audio-hidden")) {
FFplayer.classList.remove("audio-hidden");
FFplayer.classList.add("audio-shown");
} else {
FFplayer.classList.remove("audio-shown");
FFplayer.classList.add("audio-hidden");
Array.prototype.slice.call(document.querySelectorAll('audio')).forEach(function(audio) {audio.pause();});
}
})
})
And here in jquery. Thanks to you all. You show me the way :-)
jQuery (document).ready(function($){
var btns = $('[data-music]');
$(btns).each(function() {
$('[data-music]').on('click', function(e) {
var FFplayer = $(this).data('music');
$("#" + FFplayer).toggleClass("audio-hidden audio-shown");
});
});
})

jQuery display property not changing but other properties are

I'm trying to make a text editable on clicking it. Below is the code I'm trying. When the title is clicked it shows an input box and button to save it.
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>
I have changed other properties like color or changing the text of the elements and its working, but it is not applying the display property or .show()/.hide() function on the title or edit elements.
Below is my jQuery
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(){
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
$(title).show();
$(edit).hide();
}
function editTitle(){
$('.title-edit', this).show();
$('.title', this).hide();
}
Here's the jsfiddle
https://jsfiddle.net/ywezpag7/
I've added
$(title).html('abcd');
to the end to show that other properties/functions are working, but just not the display.
For checking the html change on title element you will have to check the source through developer tools cause the title element is hidden.
Where am I going wrong?
Your problem is in the function saveTitle. The first line must stop the event propagation otherwise after this function the editTitle function is called.
The snippet:
$(function(){
$('.block').on('click', editTitle);
$('.title-edit button').on('click', saveTitle);
});
function saveTitle(e){
// this line
e.stopPropagation();
var parent = $(this).closest('.block');
var title = $('.title', parent);
var edit = $('.title-edit', parent);
title.show();
edit.hide();
title.text($('.title-edit input').val());
}
function editTitle(e){
$('.title-edit', this).show();
$('.title', this).hide();
}
.title-edit{
display:none
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="block">
<div class="title">Title</div>
<div class="title-edit">
<input type="text" name="title" value="Title">
<button>Save</button>
</div>
</div>
The issue as mentioned already is that your click events are fighting. In your code, the title-edit class is within the block, so when you click on the save button it triggers events for both clicks.
The easiest and, imho, cleanest way to resolve this is to switch your click event to be called on .title, and .title-edit button. You can also simplify the code beyond what you've got there.
$(function(){
$('.title').click(editTitle);
$('.title-edit button').click(saveTitle);
});
function saveTitle(){
$('.title').show();
$('.title-edit').hide();
$(title).html('abcd');
}
function editTitle(){
$('.title-edit').show();
$('.title').hide();
}
https://jsfiddle.net/ywezpag7/7/
I tried debug your code, and I had seen, that then you click to "Save" button, handled both functions, saveTitle() and editTitle(), and in that order. Therefore, the elements initially hidden, and then shown.

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

JQuery Show/Hide Link

So here is my dilemma. Been trucking on this Jquery extreme code here and I need help telling if a certain link is showing or not. Here is what I have.
The toggles:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
(notice the only thing that is different is the icon number) These need to toggle back and forth when someone clicks the #visbilitybutton. Not sure of the best way to do this and to capture what is selected as well.
The only code I have currently makes the toggle go one way, but doesn't go back when clicked again.
$(document).ready(function () {
$('#visbilitybutton').click(function() {
$(this).replaceWith('<span class="icon icon85"></span>');
});
});
First things first, you shouldn't have multiple identical id attributes on your page. Make visibilitybutton a class.
Anyways, you can use the jQuery toggle() function to specify what to do on each consecutive click:
$(".visibilitybutton").toggle(function(){
$(this)
.attr("title","Invisible")
.find("span").toggleClass("icon84 icon85");
}, function(){
$(this)
.attr("title","Visible")
.find("span").toggleClass("icon84 icon85");
});
If you want to be more efficient, you can do it all in one fell jQuery swoop like so, with some good techniques:
var vis = ["Invisible","Visible"];
$(".visibilitybutton").click(function(){
var i = 0;
$(this)
.attr("title",vis[i])
.find("span").toggleClass("icon84 icon85");
i = (i==0)?1:0;
});
Even more so would be to make a class that hides the element when added to it and shows it when you remove it (a classname with display:none applied in the CSS works fine):
$(".visibilitybutton").click(function(){
$(this)
.toggleClass("hide")
.find("span").toggleClass("icon84 icon85");
});
You need to have unique ids; therefore, you should select the items by class. You can use toggle() to handle the consecutive clicks, and you can use toggleClass() to handle the swapping of classes.
HTML:
<span class="icon icon84"></span>
<span class="icon icon85"></span>
Javascript:
$(document).ready(function () {
$('.button').toggle(function() {
var $button = $(this);
$button.prop("title","Invisible");
$button.find('.icon85').toggleClass('icon85', 'icon84');
}, function() {
var $button = $(this);
$button.prop("title","Visible");
$button.find('.icon85').toggleClass('icon84', 'icon85');
});
});
The id attribute is supposed to be unique to each element. Change the id attribute to the class attribute for each hyperlink.
Then, in your jQuery code, get the hyperlinks by their class name:
$('.visbilitybutton').click(function() {
// code goes here
});
In your event handler, you should use test the title attribute, like so:
$('.visibilitybutton').click(function() {
$this = $(this);
if ($this.attr("title") == "Visible")
$this.attr("title", "Invisible").find("span")
.removeClass("icon85").addClass("icon84");
else
$this.attr("title", "Visible").find("span")
.removeClass("icon84").addClass("icon85");
});

jQuery Mouseover DOM

I have a number of elements (the total number of which I do not know). I want something to appear when I mouse-over any one of these elements (which is taken care of by having a mouseover bound to the shared class of these elements).
However, the thing that I want to appear on mouseover is dependent on what the cursor is over - so I need to get the DOM element under the cursor, without the luxury of being able to bind mouseover events to each element in code.
Any suggestions?
HTML:
<a id="say1" class="say" href="#" data-word="one">Say 'one'</a>
<a id="say2" class="say" href="#" data-word="two">Say 'two'</a>
<a id="say3" class="say" href="#" data-word="three">Say 'three'</a>
Javascript (with jQuery):
$(document).ready(function () {
$('.say').mouseover(function () {
alert($(this).data('word'));
});
});
Pure Javascript (without jQuery, it is not equivalent):
window.onload = function () {
var onmouseover = function (e) {
alert(e.target.getAttribute('data-word'));
};
var elems = document.getElementsByClassName('say');
for (var i = 0; i < elems.length; i += 1) {
elems[i].onmouseover = onmouseover;
}
};
Instead of calling alert function you may implement any logic.
Event delegation is your friend here.
See this post from Christian Heilmann on that topic http://www.icant.co.uk/sandbox/eventdelegation/.
HTH.
jQuery makes this easy with .each():
$('#container').bind('mouseover', function () {
$(".selector").each(function(){
// Do something $(this) = item clicked
$(this).toggleClass('.example'); // Toggle class is just an example
});
});
You can then check certain characteristics of $(this) and then do different things based on the values/characteristics.

Categories

Resources