-1

I have this code which in jQuery:

$(document).ready(function() {
    $(".link.auto_open").prop("href", "http://newlink.com/");
    $(".link.auto_open").html("Need inspiration?").fadeIn(600).css("display","inline-block");
});

-- but I need to implement this in a site which is not using jQuery. How can I change this code to native javaScript?

This is what I have tried:

<script>
    var x = document.getElementsByClassName("link.auto_open");
    x.setAttribute("href", "http://newlink.com/");
    x.innerHTML("Need inspiration?");
</script>

but it's not working

Meek
  • 3,086
  • 9
  • 38
  • 64
  • MDN is a brilliant resource for JS API's. [setAttribute](https://developer.mozilla.org/en/docs/Web/API/Element/setAttribute) (Second Google result too) – ste2425 Apr 06 '16 at 09:52
  • what have you tried? look for `setAttribute` method and '`innerHTML` in javascript. It might help – Easwar Raju Apr 06 '16 at 09:52
  • You'd have to create the [DOM ready handler](http://stackoverflow.com/questions/2304941/what-is-the-non-jquery-equivalent-of-document-ready), then get the elements with something like `querySelectorAll` and then the really hard part, you'd have to create your own [animation](http://stackoverflow.com/questions/11213259/javascript-animation) functionality. – adeneo Apr 06 '16 at 09:53
  • Also, in plain JS `prop()` is just `element.href = 'http://newlink.com/';` – adeneo Apr 06 '16 at 09:53
  • Use CSS transitions for the animation. – ste2425 Apr 06 '16 at 09:54

2 Answers2

1

First you need a reference to the .link.auto_open element. You can do that with document.querySelector: https://developer.mozilla.org/nl/docs/Web/API/Document/querySelector

Then you need to do three things:

Here's an example:

var el = document.querySelector('.link.auto_open');

el.setAttribute('href', 'http://newlink.com/');
el.innerHTML = 'Need inspiration?';
el.style.display = 'block';

Now for the fadeIn part, this could be a bit tricky with JS, but can be done rather easily with a CSS animation.

For example:

.fadeIn {
    display: block;
    animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
    0% { opacity: 0; }
    100% { opacity: 100;  }
}

As you can see, the animation belongs to the class fadeIn so we have to add that class to the element as well. And since the fadeIn class also has a display: block we can replace the last line in the JS example with:

el.classList.add('fadeIn');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

If you combine this all, you have something like this:

https://jsfiddle.net/8j8w615p/

Pimmol
  • 1,871
  • 1
  • 8
  • 14
-2

You can use the setAttribute() property of a DOM element in javascript. Example :

var ele = document.getElementById("textBoxId");
ele.setAttribute("value","James Bond");
Rakesh Bk
  • 112
  • 15