create attributes of buttons dynamically depending on div class - javascript

i have a big problem which is driving me crazy:
i have a scrolling page with lots of divs and each has a different id, one below the other and no gap between them.
at the bottom of the viewport are 4 fixed buttons which all have a click function:
$("#button1").click(function() {
$('#firstdiv').css("background-image", "url(bg1.jpg)");
$("#button2").click(function() {
$('#firstdiv').css("background-image", "url(bg2.jpg)");
$("#button3").click(function() {
$('#firstdiv').css("background-image", "url(bg3.jpg)");
$("#button4").click(function() {
$('#firstdiv').css("background-image", "url(bg4.jpg)");
as you can see the buttons are for changing the background image of the current div.
when im scrolling down and the next div comes in it, fires an event. in this event i want to change the function of each button with different attributes for example
$("#button1_2").click(function() {
$('#seconddiv').css("background-image", "url(bg5.jpg)");
and so on..
the function is the same, but it works for the second div and another bg-images...
could someone please give me an approach to do this dynamically that i dont have to make like 25 click functions for all the divs?

Change your buttons so that they look something like this (the attributes are the important things):
<button class="image-button" data-image="bg1.jpg">Text</button>
And then you could apply your event handler to all of them at once:
$(".image-button").click(function() {
var url = 'url(' + $(this).data('image') + ')';
$('#firstdiv').css('background-image', url);
});

you can do something like that:
<span class="btn" data-num="1">button1</span>
<span class="btn" data-num="2">button2</span>
jquery :
$(".btn").click(function(){
$('#firstdiv').css("background-image", "url(bg"+$(this).attr("data-num")+".jpg)");
})

Related

How to change image when two buttons are clicked?

I want to make jQuery script where I will have 10 buttons all with different colors and after user clicks on two different buttons, combination of the clicked buttons colors will be made and switch the image frame with already prepared images based on color combinations.
My question is how to put conditions for two buttons(or links) clicked.
switch me
<img src="http://placehold.it/333/fe3/img/picture2.jpg" id="bg" />
$(function() {
$('.menulink').click(function(e){
e.preventDefault();
$("#bg").attr('src',"http://placehold.it/333/3ef/img/picture1.jpg");
});
});
I want to achieve something like this but I want image to change when two buttons (or links) are clicked.
http://jsfiddle.net/maniator/Sevdm/
provided you wanted to make sure the buttons were unique when clicked, you'll want a way of tracking which have been seen. I'm using a JS Object like a Set here for compat with older browsers.
var clickCount = 0;//count the clicks
var clickTracker = {};//track which id's were clicked
var clickThreshold = 2;//the number of clicks we want before executing the if block
function clickHandler(){//callback function for the event
if(clickTracker[this.id] === undefined){//we haven't seen this id yet
clickCount++;//increment the number of buttons clicked
clickTracker[this.id] = 1;//flag for tracking the click
if(clickCount >= clickThreshold){//we saw at least clickThreshold clicks
console.log(clickCount + 'unique clicks happened!');
//your work here
}
}
}
$('.cls').click(clickHandler);//bind events
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn1' class='cls'>1</button>
<button id='btn2' class='cls'>2</button>
<button id='btn3' class='cls'>3</button>
<button id='btn4' class='cls'>4</button>
<button id='btn5' class='cls'>5</button>
You can use event delegation to track clicks on .menulink elements. using e.delegateTarget we can have the parent container hold a variable that determines if a .menulink element has been clicked previously, and if it has, we can have it change the background.
To do this I switched the click method to an on method. The on methods parameters are:
$(element).on(event, delegated selector, function)
JQuery .on documentation
Delegation simply means that instead of checking if each button has been clicked by placing an event on the button, we place an event on the container of the buttons and ask if the element that caused the event matches our delegated selector. If it does the provided function is fired. To access the parent of the delegated element within the code we can use the passed back event object, or in this case e.delegateTarget
JQuery delegateTarget documentation
Since everything in JavaScript is an Object, we can assign new properties and methods to anything that is not explicitly part of the Browser's most base architecture. This absolutely includes the body of a page.
In the code below, I place a new property clicked on the body of the page. This is added on click of the first .menulink element, and is checked upon each subsequent click.
Because of this we can know if it is a second click by determining if body.clicked is true. If it is we tell the script to change the background image.
$(function() {
$('body').on("click", ".menulink", function(e){
if(e.delegateTarget.clicked) $("#bg").attr('src',"http://placehold.it/333/3ef/img/picture1.jpg");
else e.delegateTarget.clicked = true;
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
switch me
switch me
<img src="http://placehold.it/333/fe3/img/picture2.jpg" id="bg" />
This is what I was looking for
<script>
$(document).ready(function() {
var chosenColors = [];
$(".colors button").click(function() {
chosenColors.push($(this).text())
check();
});
function check() {
if (chosenColors.length === 2) {
$(".pretty-picture").attr("src", chosenColors.sort().join("-") + ".png")
chosenColors = [];
}
}
});
</script>
<body>
<div class=colors>
<button type="button">red</button>
<button type="button">yellow</button>
<button type="button">blue</button>
</div>
<img class="pretty-picture">
</body>

Mouse out event doesn't move back outside the button

I have a button and when you hover over it, it shows some text and 2 more buttons but when I move my mouse out of it, it still stays on the hover. How do I make my code work so that it works on mouse out?
This is my Javascript:
var option1Button_Mouseout = function() {
console.log('option1Button_Mouseout()');
$('laStyle-option1-button')[0].innerHTML = outputTag;
};
var attachOption1ButtonListeners = function() {
console.log($('laStyle-option1-button')[0]);
$('laStyle-option1-button')[0].addEventListener('mouseover', this.option1Button_Mouseover);
// When you mouse out of the button it brings it back to the original
$('laStyle-option1-button')[0].addEventListener('mouseout', this.option1Button_Mouseout);
};
window.onload = function() {
this.attachOption1ButtonListeners();
};
this is what it currently looks like:
https://media.giphy.com/media/9A6MoIdWBiZVFtcHyW/source.mp4
See when I hover over it it shows text and 2 buttons, when I mouse out it should go back to the picture of the hand.
Sind it is not clear what your methods are doing, consider this example:
HTML
<div id="myDiv">
<div id="myDiv1"/>
</div>
JavaScript
$('#myDiv').on("mouseover mouseenter ", function (e) {
$("#myDiv1").show();
});
$('#myDiv').on("mouseleave mouseout", function (e) {
$("#myDiv1").hide();
});
When entering the parent div the inner div will be shown. When leaving the parent div the inner div will be hidden. Also using .on as you are using jquery.
Here is the JSFiddle: https://jsfiddle.net/GR8sk/21/
Since you're already using jQuery I would use its Mouseenter and mouseleave events like so:
$("document").ready(function(){
$(".laStyle-option1-button img").mouseenter(function(){
$(this).attr('src','https://media.giphy.com/media/xUOwGdPZ0chBWiQ6Ri/giphy.gif');
});
$(".laStyle-option1-button img").mouseleave(function(){
$(this).attr('src','https://media.giphy.com/media/l4pTgiQB2e2dpuKs0/giphy.gif');
});
});
Couple things to note:
You did not add a '.' to the beginning of your jQuery reference to laStyle-option1-button (look at how the period goes before) because its a class attribute.
You are performing unnecessary event listener loading. While this can be helpful for binding to click events, I would just use the 'bind' method to bind functions to click events:
$( "#btnButton" ).bind( "click", myFunction);
You need to change either the 'src' attribute of the image, or just remove the button completely and replace with another one. The former is better performing.

Switch between two pages with toggleClass

I've got a page with 2 buttons and 2 divs which are hidden.
When you click the first button the first div should appear, and if you click the second button the second div should appear.
I've managed to get that to work, but what I can't get to work is, that if I have the first div open, and click the second button, I would like it to show the second div and close the first div.
$(document).ready(function() {
$('button.hh').click(function() {
$(".hh_facebook").toggleClass("vis");
$(".hg_facebook").toggleClass("skjul");
});
});
$(document).ready(function() {
$('button.hg').click(function() {
$(".hg_facebook").toggleClass("vis");
$(".hh_facebook").toggleClass("skjul");
});
});
Here is my fiddle:
http://jsfiddle.net/4mWLk/4/
Best regards
Martin
your js code is a bit incorrect.
You call twice $(document).ready(function() { ... Is enough once time.
try this:
$(function(){
$("button.hh").on("click", function(){
$(".hh_facebook").show();
$(".hg_facebook").hide();
});
$("button.hg").on("click", function(){
$(".hh_facebook").hide();
$(".hg_facebook").show();
});
});
see the updated fiddle: http://jsfiddle.net/4mWLk/5/
update if you want to hide div after clicking on same button: http://jsfiddle.net/4mWLk/8/
Use toggle instead of show (for your comment at my answer)
PS: I updated CSS because there was not neccessary.
If you want it with classes so you can have more control over the effect in case you decide to change it later, you should do it like this:
http://jsfiddle.net/4mWLk/7/
$(document).ready(function() {
$('button.hh').click(function() {
$(".hh_facebook").toggleClass("skjul vis");
$(".hg_facebook").removeClass("vis").addClass("skjul");
});
$('button.hg').click(function() {
$(".hg_facebook").toggleClass("skjul vis");
$(".hh_facebook").removeClass("vis").addClass("skjul");
});
});
Html:
<div class="hh_facebook skjul">test1</div>
<div class="hg_facebook skjul">test2</div>
What it does is like this:
first the divs start with skjul class so they are in hidden state.
when a button is pressed, toggle both the skjul and vis classes (one is removed, the other is added)
make sure the second div is hidden.

Change css when tab has active class

I'm trying to change the background colour of the <body> depending on what tab specific is active.
When a tab is active, a class called 'st_view_active' is added onto the tab content. In the tab content I add a hidden div with the hex code of what my body background colour should be when that tab is active, my jQuery code looks like this:
$(document).ready(function() {
$(function(){
$('body').css('backgroundColor',$('.st_view_active').find('.background').text());
});
});
And my html code when the tab is active is following:
<div class="tab-6 st_view st_view_active" >
<div style="display:none" class="background">yellow</div>
<div class="st_view_inner">
tab 6
</div>
</div>
So when tab6 is active the background of the body should be yellow. However, this is not working, the background colour is not changing, what am I doing wrong here?
DEMO and JSfiddle
Thanks
PS: The red and blue square is the next and previous tab handler..
See here: http://jsfiddle.net/CNYDU/25/
I put the default color at the end of sColor, but you could instead grab the first view and use its color. I did it this way to cut down on testing since your fiddle is painful to work with.
$(document).ready(function() {
var hsh = window.location.hash.replace('#','');
var sColor = hsh ? $("#slidetabs_45").find("."+hsh+" .background").text() : "#3b0";
$("body").css("background-color", sColor);
$("#slidetabs_45").slidetabs({
onContentVisible:function(e){
var color = $("#slidetabs_45").find(".st_view_active .background").text();
$("body").css("background-color", color);
}
});
});
I also added the .st_view_active class to the first view so that it will start correctly.
I also added a CSS3 transition to the background color, which isn't necessary.
This sounds like a great opportunity to use data elements in html. Rather than having a hidden div with the background color you want, you can simple add a data-color attribute to your tab a tag. Then when the div is clicked you can set the color easily with an event handler.
link to an updated fiddle - http://jsfiddle.net/CNYDU/15/
Note: The next and previous tabs do not work in this example, but it should be easy to get them working, just attach a listener to each that runs
$('body').css('background-color', $(".st_tab_active").attr('data-color'));
as its callback.
Check out the livequery plugin for jQuery.
Live Query also has the ability to fire a function (callback) when it matches a new element and another function (callback) for when an element is no longer matched. This provides ultimate flexibility and untold use-cases. For example the following code uses a function based Live Query to implement the jQuery hover helper method and remove it when the element is no longer matched.
Their example:
$('li')
.livequery(function(){
// use the helper function hover to bind a mouseover and mouseout event
$(this)
.hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
}, function() {
// unbind the mouseover and mouseout events
$(this)
.unbind('mouseover')
.unbind('mouseout');
});
You should be able to adapt this to your css changes like fired events, and therefor perform your actions based on which tab is active.
I have forked Jlange's jsfiddle, which uses the data attribute, for a demo of how this plugin would be used:
http://jsfiddle.net/nj6ZY/2/
http://jsfiddle.net/nj6ZY/2/show/#tab-10 - Also works with a link to activate a specific tab
And the relevant bits:
$('.st_tabs_ul li a.st_tab_active').livequery(function(){
$('body').css('background-color', $(this).data('color'));
});
Put ID's on your tabs. Example for id="tab6":
$(document).ready(function() {
if ($('#tab6').attr('class') == 'tab-6 st_view st_view_active') {
$('body').css('background-color', 'yellow');
}
});
However, why would you attach this function to document ready only? I would bind the function to when the element is clicked...

Javascript/JQuery Execution order

I have multiple instances of a div ".gallery" and I want to pick up the id of the div the particular instance of .gallery is sitting in on click. This would then populate a variable that I can use to make the image only change in that div's gallery. Problem is that the page seems to try to do the image swap, then changes the variable, so the image doesn't change on the first click, and-worse-the first time you click on a different gallery it changes the image of the last gallery you interacted with. Currently there is a javascript alert that I have pop up every time you click a div that reports the div you clicked. I have the page in its current state here if you want to play around with it. www.ryanscasey.com/redesign
The straight javascript is as follows:
$(document).ready(function() {
var clickedDiv;
$('.gallery').click(function() {
clickedDiv = $(this).parent().parent().attr("id");
$('#' + clickedDiv + ' .thumbs img').click(function() {
$('#' + clickedDiv + ' .largeImage').html($(this).attr('alt'));
});
alert(clickedDiv);
});
});
I think this is what you want. It doesn't sound like you need to bind more than one click event. The way you had it, it would bind a click event any time a .gallery item was clicked. If this doesn't work, let me know, and we'll try to work from there.
$(document).ready(function() {
$('.gallery .thumbs img').click(function() {
var $this = $(this),
$gallery = $this.closest('.gallery'),
$large = $gallery.find('.largeImage');
$large.html($this.attr('alt'));
});
});
EDIT: I took a look at your site and I have adjusted my code. You want to bind the click event to the thumbnail not the entire gallery.

Categories