javascript replace div on each click - javascript

The following works to replace a div with a new div...
<div id = "div1" style="display:block" onclick = "replace()"><img src="1.jpg" /></div>
<div id = "div2" style="display:none"><img src="2.jpg" /></div>
<script type = "text/javascript">
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
}
</script>
What I can't figure out is how to make this work so when you click div2 it is replaced by div3 and so on.
In other words, I want to replace the div on each click more than just once. What's the best way to go about this? I'm a novice, so not sure if the above is a good start or not.
Thanks!

You could make a more generic function:
function replace( hide, show ) {
document.getElementById(hide).style.display="none";
document.getElementById(show).style.display="block";
}
Then you can create many divs and use the same function:
<div id = "div1" style="display:block" onclick = "replace('div1','div2')">...</div>
<div id = "div2" style="display:none" onclick = "replace('div2','div3')">..</div>
<div id = "div3" style="display:none" onclick = "replace('div3','div4')">..</div>
...

I will suggest you some best practices in this answer:
Use classes instead of the style property, it's way nicer for the browser.
Don't use inline event handler. See the example below.
It's not "replace" you're looking for, it's "toggling".
I suggest you use event bubbling. This way, you add a single event on the container of all your div, and you can work on this.
Alright, now for the example:
HTML:
<div id="container">
<div id="div1">..</div>
<div id="div2" class="hidden">..</div>
<div id="div3" class="hidden">..</div>
</div>
JS:
// Notice how I declare an onclick event in the javascript code
document.getElementById( 'container' ).onclick = function( e ) {
// First, get the clicked element
// We have to add these lines because IE is bad.
// If you don't work with legacy browsers, the following is enough:
// var target = e.target;
var evt = e || window.event,
target = evt.target || evt.srcElement;
// Then, check if the target is what we want clicked
// For example, we don't want to bother about inner tags
// of the "div1, div2" etc.
if ( target.id.substr( 0, 3 ) === 'div' ) {
// Hide the clicked element
target.className = 'hidden';
// Now you have two ways to do what you want:
// - Either you don't care about browser compatibility and you use
// nextElementSibling to show the next element
// - Or you care, so to work around this, you can "guess" the next
// element's id, since it remains consistent
// Here are the two ways:
// First way
target.nextElementSibling.className = '';
// Second way
// Strip off the number of the id (starting at index 3)
var nextElementId = 'div' + target.id.substr( 3 );
document.getElementById( nextElementId ).className = '';
}
};
And of course, the CSS:
.hidden {
display: none;
}
I highly suggest you read the comments in the javascript code.
If you read carefully, you'll see that in modern browsers, the JS code is a matter of 5 lines. No more. To support legacy browsers, it requires 7 lines.

Related

Change location.href with jQuery

I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>

Remove class from parent element javascript

I have a container that opens via an onclick function. I then have a cross within the container that should close the parent element however I receive a
TypeError: undefined is not an object (evaluating 'parent.id')
Code is here
<div class="post" onclick="postClick(el)">
...
...
</div>
JavaScript
function postClick(el) {
document.getElementById(el.id).classList.add("read");
}
function postClose(event) {
var parent = this.parentNode;
console.log(parent.id);
parent.id.classList.remove("read");
}
Use event.target to get the reference to the HTML element.
And you have an extra .id in the parent.id.classList expression.
function postClick(event) {
const el = event.target;
document.getElementById(el.id).classList.add("read");
}
function postClose(event) {
const el = event.target;
const parent = el.parentNode;
console.log(parent.id);
parent.classList.remove("read");
}
<div class="post" onclick="postClick(event)">
...
...
</div>
One way of doing this is using pure Javascript and bind the event listener like this
document.querySelector('#toggle').addEventListener('click', function (e) {
console.log(this.parentNode.classList.remove('read'))
});
div {
padding: 20px 50px;
}
div.read {
background-color: red;
}
<div class="read">
<button id="toggle">Remove Parent Class</button>
</div>
Jut use this and you are done : 😊
element.parentNode.classList.remove("class-name");
if the project is complex and needs interactivity more than often then you use jquery library for the interactivity.
//to remove class
$( "p" ).removeClass( "myClass yourClass" )
$("#div123").toggle(); //if you want to temp hide elements
as your code suggests the 'read' items must be disabled, you can toggle them once an event handler is wrapped over the toggle method. you can pass this or $(this) in case you want to do stuff with the owner of the function call.
well i agree some adept devs didnt like this answer, it will be surely of some help to some beginner dev in future who is looking for an alternative option to hide elements or remove classes

Use XPath or onClick or onblur to select an element and use jQuery to blur this element

*UPDATE:I am new to jQuery, as well as using XPath, and I am struggling with getting a proper working solution that will blur a dynamically created HTML element. I have an .onblur event hooked up (doesn't work as expected), and have tried using the $(document.activeElement), but my implementation might be incorrect. I would appreciate any help in creating a working solution, that will blur this element (jqInput) when a user clicks anywhere outside the active element. I have added the HTML and jQuery/JavaScript below.
Some ideas I have had:
(1) Use XPath to select a dynamic HTML element (jqInput), and then use jQuery's .onClick method to blur a this element, when a user clicks anywhere outside of the area of the XPath selected element.
(2) Use the $(document.activeElement) to determine where the .onblur should fire:
var thisTitle = input0;
var activeElement = $(document.activeElement);
if (thisTitle != activeElement) {
jqInput.hide();
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
}
I am open to all working solutions. And hopefully this will answer someone else's question in the future.
My challenge: Multiple elements are active, and the .onblur does not fire. See the image below:
NOTE: The <input /> field has focus, as well as the <div> to the left of the (the blue outline). If a user clicks anywhere outside that <input />, the blur must be applied to that element.
My Code: jQuery and JavaScript
This is a code snippet where the variable jqInput and input0 is created:
var jqInput = null;
if (jqHeaderText.next().hasClass("inline-editable"))
{
//Use existing input if it already exists
jqInput = jqHeaderText.next();
}
else
{
//Creaet a new editable header text input
jqInput = $("<input class=\"inline-editable\" type=\"text\"/>").insertAfter(jqHeaderText);
}
var input0 = jqInput.get(0);
//Assign key down event for the input when user preses enter to complete entering of the text
input0.onkeydown = function (e)
{
if (e.keyCode === 13)
{
jqInput.trigger("blur");
e.preventDefault();
e.stopPropagation();
}
};
This is my .onblur event, and my helper method to blur the element:
input0.onblur = function ()
{
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
};
inputOnBlurHandler: function (canvasObj, jqHeaderText, jqInput)
{
// Hide input textbox
jqInput.hide();
// Store the value in the canvas
canvasObj.headingText = jqInput.val();
_layout.updateCanvasControlProperty(canvasObj.instanceid, "Title", canvasObj.headingText, canvasObj.headingText);
// Show header element
jqHeaderText.show();
_layout.$propertiesContent.find(".propertyGridEditWrapper").filter(function ()
{
return $(this).data("propertyName") === "Title";
}).find("input[type=text]").val(canvasObj.headingText); // Update the property grid title input element
}
I have tried using the active element, but I don't think the implementation is correct:
var thisTitle = input0;
var activeElement = $(document.activeElement);
if (thisTitle != activeElement) {
jqInput.hide();
_layout.viewHeaderTextInput.inputOnBlurHandler(canvasObj, jqHeaderText, jqInput);
}
My HTML code:
<div class="panel-header-c">
<div class="panel-header-wrapper">
<div class="panel-header-text" style="display: none;">(Enter View Title)</div><input class="inline-editable" type="text" style="display: block;"><div class="panel-header-controls">
<span></span>
</div>
</div>
</div>
I thank you all in advance.

Append a div outside of the input parent

Im fairly new to javascript and I just can't figure this out despite my attempt in researching. How do I track the change of a input within a div and trigger an append to an outside div? My code goes as follow:
Append h3 with "Pending" once ".image-value" input has a change in value
<!-- APPEND <h3> -->
<h3>Best Overall Costume<div class="pending">Pending</div></h3>
<div>
<div class="select-form">
<img src="images/vote.jpg" data-value="image_value">
<img src="images/vote.jpg" data-value="image_value2">
<img src="images/vote.jpg" data-value="image_value3">
<img src="images/vote.jpg" data-value="image_value4">
<img src="images/vote.jpg" data-value="image_value5">
<!-- Track the change of this input -->
<input type="hidden" class="image-value" name="selected_image" value="">
</div>
</div>
I tried this:
function changeStatus(statusValue) {
$("input",".select-form").val(statusValue).trigger("change");
}
$("input",".select-form").change(function(){
if (!$(this).val()){
$("<div class='pending'>Pending</div>").appendTo($("h3").prev($(this)));
}
});
But that didn't seem to work. Any ideas?
place an empty div where you want your new div and give it an id i.e(<div id='myDiv'><div>) and then append what you want like this.
$( "#myDiv" ).append( "<div class='pending'>Pending</div>" );
You can also check Append Explained
for more explanations.
Thanks.
I've done a couple things here... First, I'm not sure why you had it all in a named function. When you're using event listeners that often isn't necessary.
Then, I don't know what the val check was for, so I reversed it.
Finally, I'm using one(), which only runs once. This case seemed to call for that.
$('.select-form').one('change', 'input', function () {
if ( $(this).val() ) { alert('asdgf');
$("<div class='pending'>Pending</div>")
.appendTo($(this).parent().prev('h3'));
}
});
Fiddle
try this:
$("input",".select-form").on("change", function(){
var $this = $(this);
if (!$this.val()){
var elem = $('<h3>Best Overall Costume<div class="pending">Pending</div></h3>');
$this.parent().parent().before(elem);
}
});
you can also place a check, that if the pending div is already added, not to add it again.
Of course this solution assumes that there are no other nested divs between the target div(before which you want to append) and the input control

Changing content of a div with Prototype or JavaScript

I have this code :
<div class="box_container">
<div class="box_container_button" id="navigator_1">
Button 1
</div>
<div class="box_container_button" id="navigator_2">
Button 2
</div>
<div class="box_container_button" id="navigator_3">
Button 3
</div>
<div class="box_container_content" style="background-color:#d5d5d5;" id="navigator_content_1">
Content 1
</div>
<div class="box_container_content" style="background-color:#00aeef; display:none;" id="navigator_content_2">
Content 2
</div>
<div class="box_container_content" style="background-color:#4db848; display:none;" id="navigator_content_3">
Content 3
</div>
</div>
If I press on the button with navigator_2, navigator_content_1 must be hidden, and navigator_content_2 showed.
How can I do this with prototype? (Or javascript if it's too stronger). Unfortunatly I can't use jQuery.
Try this
function nav(obj)
{
document.getElementById("navigator_content_1").style.display = "hidden"
document.getElementById("navigator_content_2").style.display = "hidden"
document.getElementById("navigator_content_3").style.display = "hidden"
obj.style.display = "none";
}
Add onclick="nav(this)" to each button element.
Here is my suggestion:
Give the container holding the buttons in ID (for convenience).
Change the IDs of the content containers from navigator_content_1 to navigator_1_content (again, for convenience).
Then all you have to do is to keep a reference to the currently showed content pane and you have to attach a click handler to the container holding the buttons:
// by default, the first panel is shown
var current = document.getElementById('navigator_1_content');
document.getElementById('box_container').onclick = function(event) {
event = event || window.event; // for IE
var target = event.target || event.srcElement; // for IE
current.style.display = 'none';
current = document.getElementById(target.id + '_content');
current.style.display = 'block';
};
This makes use of event bubbling. event.target has a reference to the element that was actually clicked (I don't know if the Safari bug is still present, you might have to traverse the DOM up to find the correct element). This can certainly be improved but should give you a good start. You can easily add new buttons / content panels without having to modify the code.
Here is a DEMO.
To learn more about event handling, I suggest to have a look at the excellent articles at quirksmode.org
This would use prototype and get what you want
$$('.box_container_button').each(function(element) {
element.observe('click', function(event) {
$$('.box_container_content').each(function(element) {
element.setStyle({
'display': 'none'
});
});
$('navigator_content_' + this.id.replace("navigator_", "")).setStyle({
'display': 'block'
});
});
});
http://jsfiddle.net/VENLh/
THIS solution would work even if you add more buttons / contents without changing any line in the javascript (just add the html part!)

Categories

Resources